Reputation: 12975
I have an collection doc like .
{'_id':1,
'name':'Root',
'taskId':1,
'parentId':"",
'path':[1],
'tasks':[ {"taskId":3,parentId:1,name:'A',status:'Created'},
{"taskId":4,parentId:1,name:'D',status:'Created'},
{"taskId":5,parentId:4,name:'B',status:'Created'},
{'type':'project' , 'proRef':2},
{"taskId":6,parentId:3,name:'E',status:'Started'},
{"taskId":7,parentId:6,name:'C',status:'Stopped'}]
}
Now I want to update multiple array element field ‘status’ to ‘Deleted’ which is inside JSON .Let us assume for taskId 3,4 I need to update status to Deleted . I have tried this query with $in with query($) but it is updating very first element is $in array only. In below query only taskId with 3 is getting updated not 4.
db.projectPlan.update({"_id": 1,'tasks.taskId': {$in :[3,4]}} , {$set: {'tasks.$.status': 'Deleted'}}, {upsert: false, multi: true});
How to update multiple elements in single query.Thanks in advance !!
Upvotes: 4
Views: 1442
Reputation: 42048
I'm afraid it's not possible, it's a limitation of MongoDB. From the documentation (http://docs.mongodb.org/manual/reference/operator/update-array/):
$ Acts as a placeholder to update the first element that matches the query condition in an update.
See this ticket for more details: https://jira.mongodb.org/browse/SERVER-1243
It's possible though in MongoDB shell:
db.projectPlan.find({"_id": 1}).forEach(function(plan) {
plan.tasks.forEach(function(task) {
if(task.taskId in { 3: 1, 4: 1 }) {
task.status = "Deleted";
}
});
db.projectPlan.save(plan);
});
Upvotes: 5