Python 使用$set和positional$运算符更新集合中数组中的文档

Python 使用$set和positional$运算符更新集合中数组中的文档,python,arrays,mongodb,mongodb-query,pymongo,Python,Arrays,Mongodb,Mongodb Query,Pymongo,收藏: { "shopping_list": [ { "date": 22, "drinks": [1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000, 1000], "year": 2016, "month": 11 }, { "d

收藏:

{
    "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}})
我编写的代码:

{
    "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
将目标对准数组第二个索引中的
购物列表。但在我运行它之后没有任何变化。我的代码有什么问题?

这是因为查询表达式错误

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

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\u one()
方法