1

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"
        }
    ]
}
0

2 Answers 2

2

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 } }
);
Sign up to request clarification or add additional context in comments.

Comments

1

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
  }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.