使用Pymongo在集合中指定$ push位置 [英] specifying $push location in collection using Pymongo

查看:212
本文介绍了使用Pymongo在集合中指定$ push位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在集合中使用$ push,我必须指定要向其添加信息的文档. 请考虑以下示例:

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'
                    }
                  ]
       } 

如果我只想更新"class"集合中的第一个文档("class"中的cse131),我将如何使用$ push来做到这一点?例如,如果我想更改时间"或添加通过/失败"选项?

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!

推荐答案

您使用了错误的更新运算符.您需要的是 $set 更新运算符以及位置 $ 更新操作符.

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'}
)

这篇关于使用Pymongo在集合中指定$ push位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆