3

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

@Nill Lunn, I am getting the following error Invalid modifier specified $addToset
@Mulagala Typo in the code sample. It was typed correctly everywhere else.
@Nill Lunn, can we count the matched documents, because i need to warn when there is already same member in list, Because i may face a problem while deleting a member not in list.So first i need to find a member in list
@Mulagala See here. The same basic principle applies in all drivers that support the methods. In the shell you will see the results returned immediately with MongoDB 2.6 and upwards.
@NeilLunn I have a similar requirement where I need to add/update/delete in arrays of sub-documents as well as add/update/delete in arrays of sub-documents inside the first level of sub-document arrays. I asked a question about this on SO today, because I was getting really confused.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.