Mulagala
Mulagala

Reputation: 8661

How to find and insert into sub document array list in MongoDB?

I want to insert a value to the array in the array of the sub document when the value is not already there.I have a collection like this

{
"_id" : ObjectId("53993f67ccbc960c7d05b74f"),
"groups" : [
    {
        "groupName" : "Default",
        "groupMembers" : [ ]
    },

    {
        "groupMembers" : [ ],
        "groupName" : "Family"
    },
    {
        "groupName" : "Friends",
        "groupMembers" : ["jack" ]
    }
],
"userName" : "krishna",
}

Now i want to find the a value in Friends group and if the value is not there and it should be inserted.

Upvotes: 3

Views: 2621

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151200

You want the $addToSet operator:

db.groups.update(
    { "userName": "krishna", "groups.groupName": "Friends" },
    {
        "$addToSet": { "groups.$.groupMembers": "jack" }
    }
)

Also using the same positional $ operator to match the required array element, you use $addToSet which will "push" the element onto the array if it does not exist. If it does exist then there is no update performed.

Upvotes: 3

Related Questions