Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add subdocument array element to subdocument array element in mongoDB

Tags:

mongodb

Is this possible? I have a collection C, with an array of attributes A1. Each attribute has an array of subattributes A2.

How can I add a subdocument to a specific C.A1 subdocument ?

like image 299
johnlemon Avatar asked Feb 18 '23 22:02

johnlemon


1 Answers

Here is an example.

db.docs.insert({_id: 1, A1: [{A2: [1, 2, 3]}, {A2: [4, 5, 6]}]})

If you know the index of the subdocument you want to insert, you can use dot notation with the index (starting from 0) in the middle:

db.docs.update({_id: 1}, {$addToSet: {'A1.0.A2': 9}})

This results in:

{
    "A1" : [
        {
            "A2" : [
                1,
                2,
                3,
                9
            ]
        },
        {
            "A2" : [
                4,
                5,
                6
            ]
        }
    ],
    "_id" : 1
}
like image 73
Thomas Avatar answered Apr 08 '23 22:04

Thomas