我试图推送到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
因为那时你根本没有使用位置'$'操作符。为了使用位置运算符,您需要匹配数组中的元素,然后在更新部分中指定运算符。只要改变你写的第一个查询,也包含数组元素的匹配。 –