我試圖推送到MongoDB 3.0.4中的嵌套數組。這將說明problem-這裏是在字符集的文件,我想IMAGE_4添加到埃爾默的圖像陣列:
{
"_id" : ObjectId("56084e91981824fc51693e72"),
"firstname" : "Elmer",
"lastname" : "Fudd",
"company" : "Warners",
"password" : "4567",
"galleries" : [
{
"gallery" : "1",
"images" : [
"image_1",
"image_2",
"image_3"
]
}
]
}
首先我想:
db.characters.update({"firstname":"Elmer"},{$push {"galleries.$.images":"image_4"}})
,並得到了錯誤:
"writeError" : {
"code" : 16837,
"errmsg" : "The positional operator did not find the match needed from the query. Unexpanded update: galleries.$.images"
然後我看到了SO Update an item in an array that is in an array 的解決方案,並試圖:
db.characters.update({"firstname":"Elmer"},{$push:{"galleries.0.images":"image_4"}})
哪些工作正常。我知道位置操作符$不能用於嵌套數組,但爲什麼用0代替它,在這種用法中什麼是0?我無法在Mongodb文檔中找到它。
錯誤是非常具有描述性的,你不匹配數組的一個元素。因此,請在您的更新的查詢部分中使用:{{「firstname」:「Elmer」,「galleries.gallery」:1}',以便實際匹配所需的元素。 –
@Blakes七。 db.characters.update({「firstname」:「Elmer」,「galleries.gallery」:1},{$ push:{「images」:「image_4」}})不起作用。沒有錯誤信息,但nModified:0。 – meanstacky
因爲那時你根本沒有使用位置'$'操作符。爲了使用位置運算符,您需要匹配數組中的元素,然後在更新部分中指定運算符。只要改變你寫的第一個查詢,也包含數組元素的匹配。 –