Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a sub document to sub document array in MongoDB

I have a collection in mogodb like this:

{
"_id" : ObjectId("5393006538efaae30ec2d458"),
"userName" : "shiva",
"userUnderApiKey" : 123456,
"groups" : [
    {
        "groupName" : "Default",
        "groupMembers" : [ ]
    }
]
}

I want to add a new group in the groups array as sub document, like the below

 {
"_id" : ObjectId("5393006538efaae30ec2d458"),
"userName" : "shiva",
"userUnderApiKey" : 123456,
"groups" : [
    {
        "groupName" : "Default",
        "groupMembers" : [ ]
    },

    {
        "groupName" : "Family",
        "groupMembers" : [ ]
    }
]
}

How to insert new sub document in the array of sub documents.Any help would be appriciated

like image 301
Mulagala Avatar asked Dec 12 '22 05:12

Mulagala


1 Answers

To add a new member to the array you just use $push as you normally would:

db.collection.update(
    { "_id": ObjectId("5393006538efaae30ec2d458") },
    { 
        "$push": {
            "groups": {
                "groupName" : "Family",
                "groupMembers" : [ ]
            }
        }
    }
)

If you then wanted to add members to the array that member contains then you need to match the element you want to add to:

db.collection.update(
    { 
        "_id": ObjectId("5393006538efaae30ec2d458"),
        "groups.groupName" : "Family",
    },
    { 
        "$push": {
            "groups.$.groupMembers" : "bill"
        }
    }
)
like image 105
Neil Lunn Avatar answered Dec 13 '22 19:12

Neil Lunn