Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
70 views
in Technique[技术] by (71.8m points)

python - MongoDB - adding subdocument in an array

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...