MongoDb - How can I update multiple elements of a nested object using $set?

旧城冷巷雨未停 提交于 2019-12-12 07:48:11

问题


Lets say I have the following document:

{name: 'myDoc', nestedDoc: {a: 1, b: 2, c: 3}}

And I would like to merge with the nestedDoc a new object:

{b: 20, c:30, d:40}

So the resulting object would be:

{name: 'myDoc', nestedDoc: {a: 1, b: 20, c: 30, d: 40}}

How can I go about doing this in a single query? I feel like I need multiple $set calls however object property names must be unique. In other words, I wish I could do the following:

db.myCollection.update({name: 'myDoc', nestedDoc: {$set: {b: 20}, $set: {c: 30}, $set: {d: 40}}); 

Some extra details are that the MongoDB version is 1.8.2 and I am using the NodeJS node-native driver.


回答1:


You can update by using the following:

db.myCollection.update({
    name: 'mydoc'
}, {
    $set: {
        'nestedDoc.b': 20,
        'nestedDoc.c': 30,
        'nestedDoc.d': 40
    }
})

Here is more information about update command: http://www.mongodb.org/display/DOCS/Updating#Updating




回答2:


update: this answer is not a correct update!

this works too in my app, and easy to read

db.myCollection.update({
    name: 'mydoc'
   }, 
   {
    $set: {
        nestedDoc:{
           b: 20,
           c: 30,
           d: 40,
       } 
    }
})


来源:https://stackoverflow.com/questions/7617915/mongodb-how-can-i-update-multiple-elements-of-a-nested-object-using-set

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!