Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull item by value from embedded array in Mongo

Tags:

arrays

mongodb

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}})
like image 348
raffian Avatar asked Dec 27 '22 06:12

raffian


1 Answers

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, 
like image 173
Aleksandar Vucetic Avatar answered Jan 12 '23 07:01

Aleksandar Vucetic