如何在mongodb中拉出数组元素(文档)?

All*_*uin 3 mongodb

假设集合是这样的:

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

我想删除一个文件mylist,其foo1等于bar1,看完之后有关更新MongoDB的文件我用这个:

db.mytests.update({},{$pull:{'mylist':{'mylist.$.foo1':'bar1'}}})
Run Code Online (Sandbox Code Playgroud)

但它失败了.为了找出问题,我mytests使用这个插入一个新数组:

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

然后使用db.mytests.update({},{$pull:{'anotherList':{$gt:3}}})拉取4数组中的元素 anotherList,它成功.

我认为问题出在mylist.$.foo1哪?你能告诉我删除数组中文档元素的正确方法吗?

pau*_*kow 5

尝试改变:

db.mytests.update({},{$pull:{'mylist':{'mylist.$.foo1':'bar1'}}})
Run Code Online (Sandbox Code Playgroud)

至:

db.mytests.update({},{$pull:{'mylist':{'foo1':'bar1'}}})
Run Code Online (Sandbox Code Playgroud)