我试图推到MongoDB 3.0.4中的嵌套数组。这将说明这个问题--以下是字符集合中的一个文档,我想将image_4添加到Elmer的图像数组中:
{
"_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的文档里找不到。
发布于 2015-09-28 05:59:34
在这种用法中,0
将转换为
存储在第一个文档的
galleries
字段中的基于0的数组的第一个元素,其中字段firstname
等于"Elmar“。
当然在这种情况下起作用了。但是,不能保证每个查询按相同的顺序返回数组。因此,如果您有两个图库,库1可以作为第二个数组元素返回。
这里的问题是,您的查询并没有真正反映您想要做的事情。你真正想做的是
在字段
firstname
等于"Elmar“的文档中,将"img_4”添加到galleries
中的数组元素中,其中字段gallery
等于1。
那么,我们如何做到这一点呢?基本上,您使用$
运算符的方法是正确的。但是,您的查询没有包含数组的匹配模式,这是强制性的(否则查询引擎如何才能识别用于更新的确切数组元素)。因此,您的查询需要修改一点:
db.characters.update(
// The query part
{
// Nothing new here
"firstname": "Elmar",
// Now we want to identify the gallery:
// "Of all elements in the galleries array..."
"galleries": {
// "...find the element..."
"$elemMatch":{
// "...in which the field gallery equals 1."
"gallery": "1"
}
}
},
// Update part
{
// You want to use $addToSet instead of $push here
// since you don't want to have an image twice in a gallery
"$addToSet":{
// $ operator works now since we have identified the gallery
// in the query part
"galleries.$.images":"image_4"
}
}
)
请看一看 parameter的细节。
侧注:在撰写本文时BSON文档有一个16 is的文档大小限制,因此您可能应该重新考虑您的模型。然而,这是一个完全不同的故事(如何在MongoDB中正确地模拟多到多的关系已经被问了一百万次)。
https://stackoverflow.com/questions/32814436
复制相似问题