Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I perform this in python? adding subdocument in an array

Name: xxx 
Age: xxx 
Subject : 
          Chemistry 90
          Math 100

**into** 

Name: xxx 
Age: xxx 
Subject : 
          Chemistry 90
          Math 100
          History 80 
question from:https://stackoverflow.com/questions/65661479/mongodb-adding-subdocument-in-an-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
83 views
Welcome To Ask or Share your Answers For Others

1 Answer

assuming you are using a module such as pymongo you can do the following. I'm sure there are multiple ways to do this.

from pymongo import MongoClient
mongoConn=MongoClient("mongodb://"+username+":"+password+"@<instancename>:27017")
db="<dbName>"
collection="<collection name>"
query={"Name":"XXX"}
result=mongoConn[db][collection].find_one(query)
print(result)

Then using $set you can update the value.

result['Subject']['history']=80
updates={ "$set": result['Subject']}
mongoConn[db][collection].update_one(query,updates)
result=mongoConn[db][collection].find_one(query)
print(result)

This should update {"Name": "XXX", "Age": 10, "Class": "ABC", "Course":{"Chemistry":100,"Math":90}}

To{"Name": "XXX", "Age": 10, "Class": "ABC", "Course":{"Chemistry":100,"Math":90,'history':80}}

The above is not the most efficient way of doing this as you are writing the subdocument again to the db, but you can use $addToSet as mentioned in below answer to make a more specific change.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...