4

The intention of the query below is to pull items from the locs array, where x=2 and y=9. However items with these values remain in the array after this query.

 db.myCollection.update(
       { }, //All records
       { $pull: { 'locs' : { $elemMatch : {'x' : 2 , 'y' : 9 } } } }
 )

Could anyone tell me why it's not working?

Edit: Example document:

{
  "_id" : ObjectId("55555555555"),
  "locs" : [{
      "x" : 2,
      "y" : 9
    }],
  "v" : 99
}
1
  • Can you please add an example document as well? Commented Jul 25, 2013 at 10:53

2 Answers 2

7

In general, $pull does not work like this. It removes "a value from an array" (http://docs.mongodb.org/manual/reference/operator/pull/). You can not use $elemMatch here, but neither do you have to.

So if you have a document that looks like this:

{
    'title': 'example',
    'locs': [
        { x: 2, y: 12 },
        { x: 7, y: 9 },
        { x: 2, y: 9 },
    ]
}

The follow should remove your x:2 / y:9 value pair:

db.so.update(
    {},
    { $pull: { 'locs' : { 'x' : 2 , 'y' : 9 } } }
);

Which then has:

{
    'title': 'example',
    'locs': [
        { x: 2, y: 12 },
        { x: 7, y: 9 },
    ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Ah I see, thanks for the clarification Derick. I think I need to read up on a few points including the purpose of elemMatch.
I think you understand $elemMatch just fine, it's just that $pull just wants values, and not expressions/queries.
2

I believe you need not use $elemMatch. Try with the following, it should work:

db.myCollection.update({}, {$pull: {'locs' : {'x' : 2 , 'y' : 9}}})

EDIT: or @Derick's answer, which is rather better than mine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.