Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB $pull query not remove and update the existing record

My main concern is about in mongodb documentation they use $elemMatch command for find and pull the element from array, but this is not work when i use. My document structure is

{
"_id" : ObjectId("55dea445c3ad8cac03a7ed8e"),
"email" : "[email protected]",
"groups" : [ 
    {
        "_id" : ObjectId("55dea4a4c3ad8c8005a7ed8f"),
        "name" : "All Group"
    }
]}

I want to remove groups from document using mongodb query. My Query is :

db.users.update({"_id": ObjectId('55dea445c3ad8cac03a7ed8e')}, 
{$pull: {"groups": {$elemMatch: {"_id": ObjectId('55dea4a4c3ad8c8005a7ed8f')}}}})

After executing the query, the user document not updated and groups value still there. I am following mongodb documentation as: http://docs.mongodb.org/v2.6/reference/operator/update/pull/

like image 842
Harmeet Singh Taara Avatar asked Aug 27 '15 06:08

Harmeet Singh Taara


1 Answers

You do not need $elemMatch with $pull. It's arguments are basically a "query" on the array itself:

db.users.update(
    {"_id": ObjectId('55dea445c3ad8cac03a7ed8e')}, 
    { "$pull": { "groups": {"_id": ObjectId('55dea4a4c3ad8c8005a7ed8f')}}}
)

So $pull works much in way an $elemMatch works within a query, where it's own arguments are treated as a query in the subdocument elements of the array.

It is looking at the individual array elements already, unlike a "query" portion in the document which sees the whole array.

like image 145
Blakes Seven Avatar answered Dec 07 '22 10:12

Blakes Seven