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.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
Mulagala
  • 8,231
  • 11
  • 29
  • 48

1 Answers1

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.

Neil Lunn
  • 148,042
  • 36
  • 346
  • 317
  • @Nill Lunn, I am getting the following error `Invalid modifier specified $addToset` – Mulagala Jun 12 '14 at 08:36
  • @Mulagala Typo in the code sample. It was typed correctly everywhere else. – Neil Lunn Jun 12 '14 at 08:38
  • @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 Jun 12 '14 at 08:50
  • @Mulagala See [here](http://stackoverflow.com/a/24153330/2313887). 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. – Neil Lunn Jun 12 '14 at 09:03
  • @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](http://stackoverflow.com/questions/38155298/how-to-update-mongodb-documents-with-arrays-of-sub-documents) about this on SO today, because I was getting really confused. – Web User Jul 02 '16 at 02:42