Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update embedded object inside array inside array in MongoDB

I have document like

{
    id : 100,
    heros:[
        {
           nickname : "test",
           spells : [
             {spell_id : 61, level : 1},
             {spell_id : 1, level : 2}
           ]
        }
    ]
}

I can't $set spell's level : 3 with spell_id : 1 inside spells that inside heros with nickname "test. I tried this query:

db.test.update({"heros.nickname":"test", "heros.spells.spell_id":1}, 
{$set:{"heros.spells.$.level":3}});

Errror i see is

can't append to array using string field name [spells] Thanks for help.

like image 235
Denis Ermolin Avatar asked May 05 '12 20:05

Denis Ermolin


People also ask

How do you update an object in an array in MongoDB?

Update Documents in an ArrayThe positional $ operator facilitates updates to arrays that contain embedded documents. Use the positional $ operator to access the fields in the embedded documents with the dot notation on the $ operator.

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.

How do you update an object inside another object in MongoDB?

For this, use findOneAndUpdate() in MongoDB. The findOneAndUpdate() method updates a single document based on the filter and sort criteria.

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.


1 Answers

You can only use the $ positional operator for single-level arrays. In your case, you have a nested array (heros is an array, and within that each hero has a spells array).

If you know the indexes of the arrays, you can use explicit indexes when doing an update, like:

> db.test.update({"heros.nickname":"test", "heros.spells.spell_id":1}, {$set:{"heros.0.spells.1.level":3}});
like image 137
dcrosta Avatar answered Oct 07 '22 12:10

dcrosta