【问题标题】:Update document in array in the collection using $set and positional $ operator使用 $set 和位置 $ 运算符更新集合中数组中的文档
【发布时间】:2017-04-09 00:02:52
【问题描述】:

收藏:

{
    "shopping_list": [
        {
            "date": 22,
            "drinks": [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000],
            "year": 2016,
            "month": 11
        },
        {
            "date": 23,
            "drinks": [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000],
            "year": 2016,
            "month": 11
        }
    ],
    "password": "user",
    "date_signup": "10-11-2016",
    "name": "User",
    "email": "user@user.com"
}

我制作的代码:

data_1 = [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000]
data_2 = [2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000]
con.update({"email": "user@user.com",
            "shopping_list.date": 23,
            "shopping_list.month": 11,
            "shopping_list.year": 2016},
           {"$set": {"shopping_list.$.drinks": data_2}})

也试过了(没用):

con.update({"email": "user@user.com",
            "shopping_list.date": {"$eq": 23},
            "shopping_list.month": {"$eq": 11},
            "shopping_list.year": {"$eq": 2016}},
           {"$set": {"shopping_list.$.drinks": data_2}})

在我的代码中,我使用$set 在数组的第二个索引中定位shopping_list。但是在我运行它之后没有任何变化。我的代码有什么问题?

【问题讨论】:

    标签: python arrays mongodb mongodb-query pymongo


    【解决方案1】:

    这是因为你得到了错误的查询表达式。

    使用您的查询表达式,标识要更新的文档的$ 位置更新运算符不知道该做什么。如果需要在嵌入文档上指定多个条件,则需要使用 $elemMatch 运算符。

    con.update_one({
        "email": "user@user.com", 
        "shopping_list": { "$elemMatch": {
            "date": 23,             
             "month": 11,             
             "year": 2016}
        }}, 
        {"$set": {"shopping_list.$.drinks": data_2}})
    

    另请注意,update() 实际上在 MongoDB 3.2、3.0 中已弃用。你应该使用update_one() 方法

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-24
      • 2016-07-12
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      相关资源
      最近更新 更多