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

21 views
Skip to first unread message

Allan Ruin

unread,
May 17, 2012, 11:16:05 AM5/17/12
to mongod...@googlegroups.com
Firstly, I asked the question in  stackoverflow , but ,well, no answer still. 

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' is '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 ?
I tried         db.mytests.update({'mylist.foo1':'bar1'},{$pull:{'mylist':{'mylist.$.foo1':'bar1'}}})  but no luck.

Any idea what's the problem?

Allan Ruin

unread,
May 17, 2012, 11:53:45 AM5/17/12
to mongod...@googlegroups.com
Well, I finally figure this out. Incase somebody make the same mistake and may found this helpfull.

db.mytests.update({},{'$pull':{'mylist':{'foo1':'bar1'}}})
shouldn't use 'mylist.$.foo1' as key, because 'mylist' have already make sure we want to compare out condition in the 'mylist' array. 
I was mislead by the $set example

在 2012年5月17日星期四UTC+8下午11时16分05秒,Allan Ruin写道:
Reply all
Reply to author
Forward
0 new messages