問題的另一陣列的內部的陣列刪除元素
假設我有一個文件如下:如何從嵌套使用的MongoDB
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手冊使用$(更新):
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']}
,它就會起作用。但是,這並不能解決我的問題,因爲當然,我需要那個查詢。我正在尋找一個解決方案,較好的是:
- 不需要架構更改
- 執行一個查詢/更新語句
當您嘗試使用3.0.5時,您嘗試的更新正常。值得注意的是,你不需要在這裏使用'$ in'作爲''food.fruit':'apple''也可以做同樣的事情,但是更新對我來說無論如何都能正常工作。 – JohnnyHK
@JohnnyHK,它使用$ in操作符?我需要編輯我的示例,因爲我尋找的不僅僅是「蘋果」。例如:'{$ in:['apple','orange']}'。使用你的建議,我可以做'food.fruit':'apple','food.fruit':'orange''這應該相當於使用'$ in'。 – matt
哎呀。其實,這是行不通的。我試圖看看'food.fruit'是否有'apple'或'orange'。只需要至少有一個。 – matt