MongoDB:只更新嵌套数组的一个对象

标签 mongodb

我想改变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/

相关文章:

mongodb - pymongo cursor getMore 需要很长时间

arrays - Mongoose save() 不更新数据库文档中数组中的值

mongodb - MongoDB支持女孩的getDirtyPropertyNames和getPersistentValue吗?

javascript - 错误 : Cannot find module './lib/mediaType' "(after successful login)

mongodb - 在 Mongo 中,$near 和 $nearSphere 有什么区别?

mongodb - 从 mongodb 中删除所有条目的有效方法

java - Spring Data + MongoDB 无效引用错误

node.js - Mongoose 不尊重架构并插入错误的数据类型

mongodb - 集成 Google App Engine 和 Compute MongoDB,可能吗?

mongodb - 为什么 32 位机器上的 mongodb 数据大小限制为 2GB,而不是 4GB?