我想改变group
第二个元素的第三个data
元素
{
"_id" : "wLXDvjDvbsxzfxabR",
"group" : [
{
"title" : "title 1",
"data" : [
{
"note" : "text"
}
]
},
{
"title" : "title 2",
"data" : [
{
"note 1" : "text"
},
{
"note 2" : "text"
},
{
"note 3" : "text"
}
]
}
]
}
这就是我正在做的,但它给了我一个错误的结果:
var setObject = { group.2.data.3: { 'new note': 'new text'} }
Collection.update(
{ _id: 'wLXDvjDvbsxzfxabR' },
{ $set: setObject }
);
通过这个,一个新元素被添加到组中——这不是我想要的:
{
"data" : {
"3": {
"note" : "text"
}
}
}
我只想将对象 { "note 3": "text"}
设置/更新为 { 'new note': 'new text'}
并保留这样的结构。
结果应该是
{
"_id" : "wLXDvjDvbsxzfxabR",
"group" : [
{
"title" : "title 1",
"data" : [
{
"note" : "text"
}
]
},
{
"title" : "title 2",
"data" : [
{
"note 1" : "text"
},
{
"note 2" : "text"
},
{
"new note" : "new text"
}
]
}
]
}
最佳答案
数组是零索引的,所以:
var setObject = { 'group.1.data.2': { 'new note': 'new text'} }
作为Mongodb's doc说:
To access an element of an array by the zero-based index position, concatenate the array name with the dot (.) and zero-based index position, and enclose in quotes:
'<array>.<index>'
关于MongoDB:只更新嵌套数组的一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34663467/