Question

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") }
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top