append to multi-dimensional subdocument

51 views Asked by At

I want to add a new filed like "email" for each sub document in groups

{ "_id" : 10, 
  "groups" : [ 
        { 

                "members" : ["Mark"], 
                "name" : "My Friends" 
        },
        { 

                "name" : "Colleagues" 
        }, 
        { 

                "name" : "Buddies" 
        },..... 
],.. } 

Please suggest me. Thanks in advance.

I am trying tis but its not working db.users.update({},{$push: {"groups.$.email": 'abc'} }, true, true);

1

There are 1 answers

0
parc On

To accomplish this you need to use the $elemMatch operator. Specifically, you want:

db.users.update({_id:10,groups:{$elemMatch:{name:"My Friends"}}},{$push: {"groups.$.email":"abc"}},false,true);

The important part is that the $elemMatch will set the array pointer to the exact element that matched, so you can push at that point.