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"
 }
 ]
}
asked Jan 25, 2016 at 10:18
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 } }
);
answered Jan 25, 2016 at 10:35
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
 }
});
answered Jan 25, 2016 at 10:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.