Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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.

2 Answers

0 votes
by (106k points)

To insert an element to MongoDB internal list one way of doing it would be with $push:

db.col.update( 

{ name: 'doc', 'list.id': 2 }, 

{$push: {'list.$.items': {id: 5, name: 'item5'}}}
)

0 votes
by (107k points)

You can use the following code: -

> var toInsert = {id: 5, name: 'item6'}

> db.abc.update(

            { name: 'myDocument', list: { $elemMatch: { id: 2 } } },

            { $addToSet: { 'list.$.items': toInsert } }

  )

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

Related questions

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...