4

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 !!

1
  • 1
    This is not possible as outlined in @Gergo 's answer. Your schema suggests you're looking at some sort of project management/planning tool in which case you'll probably want to have tasks in a seperate collection regardless as there are many use-cases where you'd want to query tasks individually (tasks assigned to person X, taks with status Y, etc.) Commented Dec 23, 2013 at 12:19

1 Answer 1

5

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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.