使用 $set 和位置 $ 运算符更新 collection 数组中的文档
Update document in array in the collection using $set and positional $ operator
Collection :
{
"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
作为目标。但是在我 运行 它之后没有任何变化。我的代码有什么问题?
这是因为你的查询表达式有误。
如果您需要在嵌入文档上指定多个条件,请使用 $
positional update operator which identify the document to update does not know what to do. You need to use the $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()
方法
Collection :
{
"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
作为目标。但是在我 运行 它之后没有任何变化。我的代码有什么问题?
这是因为你的查询表达式有误。
如果您需要在嵌入文档上指定多个条件,请使用 $
positional update operator which identify the document to update does not know what to do. You need to use the $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()
方法