2

I am trying to update an array field in an subdocument array in my collection. My collection looks like this:

{
 _id:"1",
 employees:[{ eid:"2",
              ename:"test",
              is_user:true
             },
             { eid:"3",
              ename:"test2",
              is_user:true
             }
           ]
}

I am trying to update the is_user status and am trying it the following way:

db.users.update({_id:"1","employees.eid":"2"},{$set:"employees.$.is_user":true},true);

I also tried :

db.users.update({_id:"1","employees.$.eid":"2"},{$set:"employees.$.is_user":true},true);

But when I run a find, for the query:

db.users.find({_id:"1","employees.eid":"2"});

it still gives me nothing. Can anybody help me on this ? Thank you..

1 Answer 1

5

That does work.

> db.test.insert({_id:"1", employees:[{ eid:"2", ename:"test", is_user:true }, { eid:"3", ename:"test2", is_user:true } ] })
> db.test.find({_id:"1","employees.eid":"2"});
{ "_id" : "1", "employees" : [  {   "eid" : "2",    "ename" : "test",  "is_user" : true },  {   "eid" : "3",    "ename" : "test2", "is_user" : true } ] }

For the $ operator you want to use it like:

> db.test.insert({_id:"1", employees:[{ eid:"2", ename:"test", is_user:false }, { eid:"3", ename:"test2", is_user:false } ] })
> db.test.find({_id:"1", "employees.eid":"2", "employees.is_user": true});
> db.test.update({_id:"1", "employees.eid":"2"}, {$set: {"employees.$.is_user": true}});
> db.test.find({_id:"1", "employees.eid":"2", "employees.is_user": true});
{ "_id" : "1", "employees" : [  {   "eid" : "2",    "ename" : "test",   "is_user" : true },     {   "eid" : "3",    "ename" : "test2",  "is_user" : false } ] }

Notice how the insert of is_user is set to false on both objects in the array and after the update the matching object is updated from false to true, is that what you are looking for?

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

5 Comments

yes.. it does, but I wanna just get the array element I wanna update. When I run an update, the is_user field is not updated.
Is there a typo on one of the queries u typed, because I dont see an update query.
Even this doesnt work for me :( db.users.update({_id:"1","employees.eid":"2"},{$set:{"employees.$.is_user":true}},true);
Sorry, missed the update query, you are right, just copied it.
Pretty much what my update was doing.. But got it working now.. Thanks a lot dude.. I was trying with the positional operator on the 'query' part, but guess thats not rt.. Thanks a ton again :) People like you, get us going :) Thanks for those super quick replies

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.