Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

mongodb

set

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.

like image 852
Aaron Silverman Avatar asked Oct 01 '11 03:10

Aaron Silverman


People also ask

How do I update multiple elements in MongoDB?

To update multiple elements, use []. The[] is an all positional operator indicating that the update operator should modify all elements in the specified array field.

How do I update nested objects?

To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.

How do I update a nested array in MongoDB?

Update Nested Arrays in Conjunction with $[]The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.


1 Answers

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:

  • Update Documents
like image 72
Dmitry Avatar answered Sep 28 '22 11:09

Dmitry