Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDb: Query not pulling item from array - why?

Tags:

mongodb

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
}
like image 736
UpTheCreek Avatar asked Jan 13 '23 19:01

UpTheCreek


1 Answers

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 },
    ]
}
like image 161
Derick Avatar answered Jan 15 '23 10:01

Derick