lostinthebits
lostinthebits

Reputation: 661

mongodb replace all instances of certain value for subdocument

My collection (called "workers"):

"_id" : "500"
"type" : "Manager",
"employees" : [{
"name" : "bob"
"id" : 101
},{
"name" : "phil"
"id" : 102
}]

Goal: for every _id that is a type: Manager AND that contains a subdocument that has an "id" of 102: replace 102 with 202.

Desired End result:

"_id" : "500"
"type" : "Manager",
"employees" : [{
"name" : "bob"
"id" : 101
},{
"name" : "phil"
"id" : 202
}]

I have tried:

db.workers.update({type:'Manager','employees.id':'102'},{$set:{'employees.id':'202'}},{multi:true})

I then did the following two things to verify:

db.workers.find({type: "Manager", 'employees.id': 102}).count()

I get a result of 9.

I also tried this to verify:

db.workers.find({$and: [{type: "Manager"},{"employees.id":60}]}).count()

This returned 0.

I am pretty confused at this point. Is my update wrong? is my find wrong? Is it both? Is the '9' result wrong? Is the '0' wrong?

Upvotes: 3

Views: 2936

Answers (1)

JohnnyHK
JohnnyHK

Reputation: 311855

You need to use the $ positional update operator to update the specific element that matched your query. Your update is also using values of '102' and '202' which makes the update try and match strings when those fields are numbers.

Your update should look like this instead:

db.workers.update(
    {type: 'Manager', 'employees.id': 102}, 
    {$set: {'employees.$.id': 202}}, 
    {multi: true})

Upvotes: 3

Related Questions