Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pull a array element (which is document) in mongodb?

Tags:

mongodb

Suppose the collection is like this:

db.mytests.find()
{ "_id" : ObjectId("4fb277b89b8295a790efde44"), 
"mylist": [ 
    { "foo1" :"bar1", "foo2" : "bar2" }, 
    {"foo1" : "bar3", "foo2" : "bar4" } 
], 
"nonlist" : "nonlistVal" }

I want to remove a document in mylist whose foo1 equal to bar1, after reading mongodb document about updating I used this:

db.mytests.update({},{$pull:{'mylist':{'mylist.$.foo1':'bar1'}}})

but it failed. To figure out the problem I insert a new array into mytests using this:

db.mytests.update({},{$set:{'anotherList':[1,2,3,4]}})

and then using db.mytests.update({},{$pull:{'anotherList':{$gt:3}}}) to pull the element 4 in array anotherList ,it succeed.

I supposed the problem is with the mylist.$.foo1 ? Can you tell me the right way to remove a document element in a array?

like image 811
Allan Ruin Avatar asked Jul 12 '26 23:07

Allan Ruin


1 Answers

Try changing:

db.mytests.update({},{$pull:{'mylist':{'mylist.$.foo1':'bar1'}}})

to:

db.mytests.update({},{$pull:{'mylist':{'foo1':'bar1'}}})
like image 127
paulmelnikow Avatar answered Jul 17 '26 23:07

paulmelnikow



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!