Home:ALL Converter>Adding an element to a sub array of an array in MongoDB

Adding an element to a sub array of an array in MongoDB

Ask Time:2017-01-03T19:48:08         Author:Satya Narayana

Json Formatter

I want to create a mongodb document structure like below.

data:[[{a:b},{b:c}],[{e:f}],[{f:g},{j:h},{i:l}]]

This structure will allow me to add new sub array element, 4th one to the existing data array which contains three sub arrays in the above example, if required.

I am able to add new sub array element using below command from mongodb shell.

db.xyz.update({'id':'A01'},{$push:{data:[]}},{})

However, I am unable to findout solution for pushing data in to respective arrays. The following command is not working.

db.xyz.update({'id':'A01'},{$push:{data[0]:{$push:{a:b}}}},{})

Author:Satya Narayana,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/41442843/adding-an-element-to-a-sub-array-of-an-array-in-mongodb
yy