MongoDb - How can I updated multiple elements of a

2019-03-25 15:01发布

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 is that the mongodb version is 1.8.2 and I am using the nodejs node-native driver.

标签: mongodb set
1条回答
走好不送
2楼-- · 2019-03-25 15:27

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

查看更多
登录 后发表回答