MongoDB $pull query not remove and update the existing record
Asked Answered
C

1

12

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/

Cinematography answered 27/8, 2015 at 6:50 Comment(2)
possible duplicate of How to remove array element in mongodb?Rottenstone
possible duplicate of MongoDB, remove object from arrayReimpression
R
18

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.

Reincarnation answered 27/8, 2015 at 6:52 Comment(4)
Thanks @Blakes Seven this is work for me. But i am confuse about mongodb documentation, because in documentation they use $elemMatch query.Cinematography
@HarmeetSinghTaara No they do not. I know the piece of documentation you are referring to but if you read carefully it actually says: " In fact, the following operation will not pull any element from the original collection.". So it is in fact meant to be an example of what not to do, as people make the common mistake of assuming $elemMatch needs to be applied. It does not. Read carefully.Reincarnation
Thanks @Blakes Seven, i have query more, how we remove doucment from array of array like mention in documentation as below: { _id: 1, results: [ { item: "A", score: 5, answers: [ { q: 1, a: 4 }, { q: 2, a: 6 } ] }, { item: "B", score: 8, answers: [ { q: 1, a: 8 }, { q: 2, a: 9 } ] } ] }. Query is : db.survey.update( { }, { $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } }, { multi: true } )Cinematography
@HarmeetSinghTaara Well you can always ask another question, which is generally best rather than asking in comments. But the answer is faily well described in the documentation.Reincarnation

© 2022 - 2024 — McMap. All rights reserved.