How to insert an element to MongoDB internal list?

Guy Korland picture Guy Korland · Dec 21, 2012 · Viewed 62.6k times · Source

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.

Answer

Sammaye picture Sammaye · Dec 21, 2012

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.