问题
假设我有以下文档:
doc = {
"_id" : ObjectId("56464c726879571b1dcbac79"),
"food" : {
"fruit" : [
"apple",
"orange"
]
},
"items" : [
{
"item_id" : 750,
"locations" : [
{
"store#" : 13,
"num_employees" : 138
},
{
"store#" : 49,
"num_employees" : 343
}
]
},
{
"item_id" : 650,
"locations" : [
{
"store#" : 12,
"num_employees" : 22
},
{
"store#" : 15,
"num_employees" : 52
}
]
}
]
}
我想删除该元素
{'#store#' : 12, 'num_employees' : 22}
但仅当以下条件为真时:
food.fruit
包含值apple
或orange
item_id
具有 id650
我的尝试解决方案
我尝试了以下方法:
db.test.update({"food.fruit" : {"$in" : ["apple", "orange"]}, "items.item_id":650},{$pull:{'items.$.locations':{'store#':12,'num_employees':22}}})
更新不起作用。有趣的是,如果查询中的$in运算符部分被删除,则可以正常工作。我使用的是MongoDB v3.0.6,并咨询了MongoDB手册,以了解$(update)的使用:
https://docs.mongodb.org/manual/reference/operator/update/positional/
文档包含一个有趣的段落: Nested Arrays
The positional $ operator cannot be used for queries which traverse more than one array, such as queries that traverse arrays nested within other arrays, because the replacement for the $ placeholder is a single value
当然,我的查询跨越了不止一个数组。如果我从查询中移除'food.fruit' : {$in : ['apple']}
,它是可行的。然而,这并不能解决我的问题,因为我需要那个查询条件。我正在寻找一种解决方案,最好满足以下条件:
- 不需要更改模式
- 可以在一个查询/更新语句中执行
$in
,因为'food.fruit': 'apple'
可以完成相同的操作,但是对我来说,无论哪种方式更新都可以正常工作。 - JohnnyHK{$in : ['apple', 'orange']}
。使用您的建议,我可以使用'food.fruit':'apple','food.fruit':'orange'
,这应该等同于使用$in
。 - mattfood.fruit
是否有apple
或orange
。只需要至少有其中一个。 - matt$in
确实可以正常工作,因为您所引用的文档中提到的限制是指尝试在嵌套数组中(即数组的第一层之外)使用$
。 - JohnnyHK{'food.fruit':'apple','food.fruit':'orange'}
与{'$in':['apple','orange']}
不等同。 - matt