Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert an element to MongoDB internal list?

I have the following doc stored in MongoDB:

{     name: 'myDoc',     list: [         {             id:1             items:[                 {id:1, name:'item1'},                 {id:2, name:'item2'}             ]         },         {             id:2             items:[                 {id:1, name:'item1'},                 {id:3, name:'item3'}             ]         }     ] } 

I found a way to add an element to 'list' using $addToSet but I couldn't find a way to add to a specific list of 'items' an item.

e.g. I get the following:

{id:5, name:'item5'}  

and I want to add it to the element's item in the list with id:2.

like image 330
Guy Korland Avatar asked Dec 21 '12 09:12

Guy Korland


People also ask

How do I add an element to an array in MongoDB?

If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.

How do I add a field to a collection in MongoDB?

To add field or fields to embedded documents (including documents in arrays) use the dot notation. See example. To add an element to an existing array field with $addFields , use with $concatArrays .


2 Answers

One way of doing it would be with $push:

db.col.update(     { name: 'doc', 'list.id': 2 },      {$push: {'list.$.items': {id: 5, name: 'item5'}}} ) 

http://docs.mongodb.org/manual/reference/operator/push/

You can also replace $push with other operators like (possibly) $addToSet to get the exact results you are looking for.

like image 72
Sammaye Avatar answered Sep 17 '22 22:09

Sammaye


You can use this: -

> var toInsert = {id: 5, name: 'item6'} > db.abc.update(             { name: 'myDoc', list: { $elemMatch: { id: 2 } } },             { $addToSet: { 'list.$.items': toInsert } }   ) 

The query part will find the document from the list array with id = 2. Then we use $ positional element to add a new element at that array index.

See positional $ operator


You can also replace list: {$elemMatch: {id: 2}} with just 'list.id': 2.

But using $elemMatch will be better, when you want to update based on multiple elements of your array. For e.g., when your matching criteria is id and some another field in the array say length: -

list: {$elemMatch: {id: 2, length: 5}} 
like image 37
Rohit Jain Avatar answered Sep 20 '22 22:09

Rohit Jain