specifying $push location in collection using Pymongo

被刻印的时光 ゝ 提交于 2019-12-12 04:16:53

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!