Search code examples
mongodbmongodb-querymongodb-update

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" : "james@user.com",
"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/


Solution

  • 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.