仅查找和替换文档中的某些字段

时间:2017-06-14 10:39:17

标签: javascript mongodb mongodb-query

我有一个像这样的mongo文档:

{
    "_id" : "EimL8Hf5SsCQKM7WP",
    "enable" : "no",
    "collector" : [ 
        {
            "name" : "prod",
            "enable" : "no",
            "transport" : {
                "address" : {},
                "port" : "8000",
                "protocol" : "http-secure"
            },
            "authentication" : {},
            "notify-syslog" : "yes"
        }, 
        {
            "name" : "test",
            "enable" : "no",
            "transport" : {
                "address" : {},
                "port" : "8000",
                "protocol" : "http-secure"
            },
            "authentication" : {},
            "notify-syslog" : "yes"
        }
    ],
   "misc" : {
        "createdBy" : "someuser",
        "updatedBy" : "someuser",
    }
}

我向用户显示mongo文档as an autoform的某些字段,以便对其进行编辑。由于隐藏了其他字段,因此表单的结果将仅包含已公开的字段。

我最终得到了一个修改过的文档对象:(密切关注" name"字段)

{
    "enable" : "no",
    "collector" : [ 
        {
            "name" : "someohername",
        }, 
        {
            "name" : "anothername",
        }
    ],
    "misc" : {
        "createdBy" : "someuser",
        "updatedBy" : "anotheruser",
    }
}

我目前的要求是以某种方式将两个文档合并在一起,使得初始文档包含已修改文档的所有字段及其字段。

结果:

{
    "_id" : "EimL8Hf5SsCQKM7WP",
    "enable" : "no",
    "collector" : [ 
        {
            "name" : "someothername",
            "enable" : "no",
            "transport" : {
                "address" : {},
                "port" : "8000",
                "protocol" : "http-secure"
            },
            "authentication" : {},
            "notify-syslog" : "yes"
        }, 
        {
            "name" : "anothername",
            "enable" : "no",
            "transport" : {
                "address" : {},
                "port" : "8000",
                "protocol" : "http-secure"
            },
            "authentication" : {},
            "notify-syslog" : "yes"
        }
    ],
   "misc" : {
        "createdBy" : "someuser",
        "updatedBy" : "anotheruser",
    }
}

如果您注意到上述情况,则只保留名称字段,同时保留其余字段。

我尝试使用collection.update({id}, $set:{<<modified_docuemnt}});直接更新文档,但它正在用collector

中传递的内容替换整个$set字段

我到底该怎么做?如果我使用mongodb直接在JSONjavascript对象中进行更改,则无关紧要。

0 个答案:

没有答案