问题
I'm wondering how to use $push in a collection where I have to specify which document I want to add information to. Please consider the following example:
student1 = {
'name': 'Adam',
'year': 'sophomore',
'age': 20,
'class':[
{
'className': 'cse131',
'time': '2:30',
'finalGrade': 'A'
},
{
'className': 'cse240',
'time': '9:30',
'finalGrade': 'B'
}
]
}
If I wanted to update only the first document in the 'class' collection (the cse131 in 'class'), how would I use $push to do this? For example, if I wanted to change the 'time' or add a 'pass/fail' option?
The push format I am currently using to add new documents to the collection looks like this:
classNameInput = str(input("Class name?: "))
timeInput = str(input("Time of class?: "))
finalGradeInput = str(input("Final grade in class?: "))
collection.update(
{
'name' : 'Adam'
},
{
'$push': {
'class':{
'className' : classNameInput,
'time': timeInput,
'finalGrade': finalGradeInput
}
}
},
True)
I don't think this format would allow me to modify existing documents in a collection or push new field value pairs into existing documents in a collection. Thanks in advance!
回答1:
You are using the wrong update operator. What you need is the $set update operator and the positional $ update operator.
db.collection.update_one(
{'class.className': 'cse131'},
{'$set': {'class.$.time': '3:30'}} # or {'class.$.status': 'pass'}
)
来源:https://stackoverflow.com/questions/34664239/specifying-push-location-in-collection-using-pymongo