2

I have a MongoDB record as follow:

"id": 1,
"Tasks": [
    {
        "description": "BLAH",
        "Tags": [
            {
                "Name": "test",
                "tagID": "YRG+crq3SJucvlUwTo/uSg=="
            },
            {
                "Name": "Cars",
                "tagID": "ObwiiZpNTOGECgHb1HehHg=="
            }
        ]

    },
    ......
  ]

I'm trying to delete the object from 'Tags' with the 'Name: test' by reference to its 'tagID'. The query I have deletes the whole record within 'Tasks' not just that particular Tags object.

db.user.update({ 'id': 1 }, 
    { 
        '$pull': { 'Tasks': {'Tags.tagID': "YRG+crq3SJucvlUwTo/uSg==" }}
    },
    { '$multi': 'true' }
)

How can I ammend my query to only remove that particular tag and not remove the entire record?

styvane
  • 59,869
  • 19
  • 150
  • 156
user94628
  • 3,641
  • 17
  • 51
  • 88

3 Answers3

1

Use the positional operator $ together with the $pull update operator to remove the specific array element object:

db.user.update({"id": 1, "Tasks.description": "BLAH"},
   {
       "$pull": {"Tasks.$.Tags" : { "tagID": "YRG+crq3SJucvlUwTo/uSg==" }}
   },
   { multi: true}
);
chridam
  • 100,957
  • 23
  • 236
  • 235
1

Using Pymongo and the $ operator

col.update({"id": 1, "Tasks.description": "BLAH"},
    {
           "$pull": {"Tasks.$.Tags" : { "tagID": "YRG+crq3SJucvlUwTo/uSg==" }}
    }, multi=True 
)
styvane
  • 59,869
  • 19
  • 150
  • 156
0

I think you are looking for the $unset command. Reference here.

Miguel A. Arilla
  • 5,058
  • 1
  • 14
  • 27