Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb: remove subdocument with where clause that includes document & subdocument

Tags:

mongodb

Here is my collection (workers):

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

First: this is NOT an array so $pullAll will not work or other array commands. All I want to do is: (1) search the collection for id 101 in ALL subdocuments with type Manager. (2) If 101 exists in a "Manager" subdocument, I want to remove item 103.

I have been pouring over the interwebs for two days on this issue and cannot figure it out.

I've tried this (and many other variations):

db.workers.update( {"type":"Manager","employees.id":101},{$pull : {"employees.id" : {"id" : 103}}},false,true)
like image 857
lostinthebits Avatar asked Nov 17 '25 17:11

lostinthebits


1 Answers

The syntax of your $pull object is off. Try this instead:

db.workers.update({"type":"Manager","employees.id":101},
    {$pull : {"employees" : {"id" : 103}}},false,true)

To confirm they were removed:

db.workers.find({
    type: "Manager", 
    $and: [{'employees.id': 101}, {'employees.id': 103}]
})
like image 83
JohnnyHK Avatar answered Nov 19 '25 10:11

JohnnyHK