MongoDB pull element from array two levels deep

天涯浪子 提交于 2019-11-28 11:50:32

问题


I have a collection with the following items :

{ "Queries" : [  {  "Results" : [  {  "id" : 1 },  {  "id" : 2 } ] } ], "_id" : ObjectId("51ddb6f9b18996be485cba6f") }
{ "Queries" : [  {  "Results" : [  {  "id" : 0 },  {  "id" : 3 } ] } ], "_id" : ObjectId("51ddb701b18996be485cba70") }
{ "Queries" : [  {  "Results" : [  {  "id" : 1 },  {  "id" : 2 } ] } ], "_id" : ObjectId("51ddb705b18996be485cba71") }
{ "Queries" : [  {  "Results" : [  {  "id" : 1 },  {  "id" : 2 },  {  "id" : 4 } ] } ], "_id" : ObjectId("51ddb70db18996be485cba72") }
{ "Queries" : [  {  "Results" : [  {  "id" : 1 },  {  "id" : 2 },  {  "id" : null } ] } ], "_id" : ObjectId("51ddb7e4b18996be485cba73") }

The "Queries" field on my documents contains an array of subdocuments. These subdocuments contain an array of another subdocument.

I want to remove all entries in the "Results" field where the documents "id" field is 1.

I tried the following without success :

update({}, {$pull :{"Queries.Results": {"id":1}}}, {"multi":true})
update({}, {$pull :{"Queries.Results.id":1}}, {"multi":true})

How would I achieve this in MongoDB?

EDIT: Here is the expected result of find() after the update

{ "Queries" : [  {  "Results" : [  {  "id" : 2 } ] } ], "_id" : ObjectId("51ddb6f9b18996be485cba6f") }
{ "Queries" : [  {  "Results" : [  {  "id" : 0 },  {  "id" : 3 } ] } ], "_id" : ObjectId("51ddb701b18996be485cba70") }
{ "Queries" : [  {  "Results" : [  {  "id" : 2 } ] } ], "_id" : ObjectId("51ddb705b18996be485cba71") }
{ "Queries" : [  {  "Results" : [  {  "id" : 2 },  {  "id" : 4 } ] } ], "_id" : ObjectId("51ddb70db18996be485cba72") }
{ "Queries" : [  {  "Results" : [  {  "id" : 2 },  {  "id" : null } ] } ], "_id" : ObjectId("51ddb7e4b18996be485cba73") }

回答1:


This is the query you have to use:

db.collection.update( { "Queries.Results.id":1 }, { $pull: { "Queries.$.Results": {"id":1} } } )

You need to specify the "where" clause in order to find the document to update. You are also missing the positional operator $, you have to use it because Queries can have multiple Results.



来源:https://stackoverflow.com/questions/17579703/mongodb-pull-element-from-array-two-levels-deep

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!