raffian
raffian

Reputation: 32066

Pull item by value from embedded array in Mongo

I want to pull a specific item from an embedded array...assume the following mongo document....

db.test.find()

{
  id:1,
  comments : 
   [
     { cid: 1 },
     { cid: 2 },
     { cid: 3 },
     { cid: 4 },
     { cid: 5 }
   ]
}

I want to remove an item from the comments array by cid, not by position. I've tried all of these but none of them appear to work. I've tried using the dot notation, but that does not seem to have any effect. I tried the last post suggestion from How to Delete-nth element from array, but no luck...

db.test.update({ 'comments.cid' : 5}, {"$pull" :{"comments":{"cid":"3"}}}    )
db.test.update(  {id: 1}, {"$pull" : {"comments" : { "cid" : "3"}}},false,false)
db.test.update(  {id: 1}, {"$pull" :{"comments.cid" :3}})

Upvotes: 5

Views: 7410

Answers (3)

Amit Kumar
Amit Kumar

Reputation: 417

Just wanted to modify the answer so that it can delete multiple objects from an array.

db.test.update(  {id: 1}, {"$pullAll" : {"comments" : [{ "cid" : "3"},{ "cid" : "2"}]}})

This answer has been updated and it works with mongoose too

Upvotes: -2

raffian
raffian

Reputation: 32066

These worked too...

db.test.update({comments:{cid:4} }, 
                    {$pull:{comments:{cid:4}},  
                      $inc:{commentCount: -1}})

db.test.update({"comments.cid" : 17}, 
                     {$pull:{ comments:{cid: 17}}, 
                      $inc:{commentCount:-1}})

Upvotes: 2

Aleksandar Vucetic
Aleksandar Vucetic

Reputation: 14953

this should work:

db.test.update(  {id: 1}, {$pull :{comments: {cid :3}}})

also, in your document, you have: id: 1 without comma at the end, it shold be:

id:1, 

Upvotes: 12

Related Questions