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
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"
}
}
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With