user3142695
user3142695

Reputation: 17322

mongoDB: Update nested array object

I would like the nested object with the id BAHx9KeKjuMePce6f to be updated:

{
    "_id" : "sgG6G9XTvvjj7uxwQ",
    "target" : [
        {
            "title" : "content",
            "id" : "ePce6fBAHx9KeKjuM"
        },
        {
            "title" : "content",
            "id" : "BAHx9KeKjuMePce6f" <--
        }
    ]
}

So this is what I tried:

var newData = { title: "new", one: "more", id: 'BAHx9KeKjuMePce6f' };

Collection.update(
    { _id: 'sgG6G9XTvvjj7uxwQ', 'target.id': 'BAHx9KeKjuMePce6f' }, 
    { $set: newData }
);

The result should be:

{
    "_id" : "sgG6G9XTvvjj7uxwQ",
    "target" : [
        {
            "title" : "content",
            "id" : "ePce6fBAHx9KeKjuM"
        },
        {
            "title": "new", 
            "one": "more",
            "id" : "BAHx9KeKjuMePce6f"
        }
    ]
}

Upvotes: 1

Views: 208

Answers (2)

Alex
Alex

Reputation: 21766

You need the use the positional parameter $ to indicate you want to update the array element, rather than the root of the document, see the documentation:

Collection.update({
  _id: 'sgG6G9XTvvjj7uxwQ',
  'target.id': 'BAHx9KeKjuMePce6f'
}, {
  $set: {
    "target.$": newData
  }
});

Upvotes: 1

Volodymyr Synytskyi
Volodymyr Synytskyi

Reputation: 4055

In order to update specific element in array you can use mongodb positional $ operator.

Try the following query:

var newData = { title: "new", one: "more", id: 'BAHx9KeKjuMePce6f' };

Collection.update(
    { _id: 'sgG6G9XTvvjj7uxwQ', 'target.id': 'BAHx9KeKjuMePce6f' }, 
    { $set: { 'target.$': newData } }
);

Upvotes: 2

Related Questions