Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB using $pull to delete dictionary in an array sub-document

I'm trying to delete the following dict in this array:

{
"ProjectID": "8ToGTAUjT+CbcH68ZYuW8Q=="
"Tasks": [
    {
        "description": "",
        "title": "testcounter",
        "notes": "",
        "percentComplete": "100",
        "completedDate": {
            "hour": "12",
            "year": "2014",
            "day": "14",
            "minute": "43",
            "month": "11"
        },
        "completed": "",
        "ProjectID": "8ToGTAUjT+CbcH68ZYuW8Q==",
        "TaskID": "JxHddpQNSguzOqg1sdsdKtyQ=="
    },
    ......
 ],
 ......
 }

Tasks is a sub-document in this record.

I try to delete with this:

 db.projects.update({'ProjectID': "8ToGTAUjT+CbcH68ZYuW8Q=="}, 
                      {'$pull': {'Tasks.TaskID': "JxHddpQNSguzOqg1sdsdKtyQ=="}})

This however does not delete this sub-document. How can this dict in the array be deleted?

like image 557
user94628 Avatar asked Dec 14 '14 16:12

user94628


People also ask

How do I remove a specific element from an array in MongoDB?

To remove an element, update, and use $pull in MongoDB. The $pull operator removes from an existing array all instances of a value or values that match a specified condition.

How do you remove an element from a doubly nested array in a MongoDB document?

To remove an element from a doubly-nested array in MongoDB document, you can use $pull operator. Now field "UserZipCode": "20010" has been removed from a doubly-nested array.


1 Answers

Try to use this code:

db.projects.update(
  {'ProjectID': "8ToGTAUjT+CbcH68ZYuW8Q=="}, 
  {'$pull': {Tasks:{ TaskID: "JxHddpQNSguzOqg1sdsdKtyQ=="}}}
)

The $pull expression applies the condition to each element of the tasks array as though it were a top-level document.

like image 155
Alex Lisovoy Avatar answered Sep 24 '22 10:09

Alex Lisovoy