Home > OS >  how to add element in nested array of objects of array in mongodb
how to add element in nested array of objects of array in mongodb

Time:11-26

This image contains my data ,
I am using mongodb as database and mongoose for connection
I want to push elements in topics array and in subTopics array

CodePudding user response:

You can use arrayFilters for the task , example:

This will push new element={test:1} in the topics array with element with sessionName:'Java':

 db.c.update( { name: "class 1" } , { $push: { 'sessions.$[x].topics':{test:1 } } } , { arrayFilters : [{ 'x.sessionName':'Java' }] }  )

This will push element=1 in the subTopics array with _id:1 from sessions with sessionName='Java':

 db.c.update( { name: "class 1" } , { $push: { 'sessions.$[x].topics.$[y].subTopic':1 } } , { arrayFilters : [{ 'x.sessionName':'Java' },{'y._id':1}] }  )
  • Related