Hunter Jansen
Hunter Jansen

Reputation: 25

Removing a subdocument from array in MongodDB

I'm working with node and mongodb and having an issue removing a subdocument from an array in my collection that I can't seem to figure out.

A sample document from my 'cardHolders' collection looks like(stripped of other fields for brevity):

{
    "_id" : ObjectId("51ee899ec15d5aaff39d3352"),
    "cards" : [
            {
               "rfid_id" : ObjectId("51ee899ec15d5aaff39d335a")
            }
    ]
}

What I'm attempting to do is find all cardHolder documents that have a subdocument with a rfid_id value in the cards array.

I've tried the mongo command:

db.cardholders.update({}, 
    {$pull:{ "cards": {"rfid_id": ObjectId("51ee899ec15d5aaff39d335a")}}},
    false, false)

And while I don't get any syntax errors, no documents in my collection are effected - Any assistance on this matter would be greatly appreciated!

Edit with full document details:

{
    "_id" : ObjectId("51ee899ec15d5aaff39d3353"),
    "first" : "first",
    "last" : "last",
    "email" : "email",
    "phone" : "555 555 5555",
    "userRole" : "su",
    "cards" : [
            {
                    "rfid_id" : ObjectId("51ee899ec15d5aaff39d3359")
            }
    ],
    "zones" : [
            {
                    "zone_id" : ObjectId("51ee899ec15d5aaff39d3357")
            }
    ]
}

Upvotes: 1

Views: 3302

Answers (1)

Derick
Derick

Reputation: 36794

Your example works just fine:

db.so.drop();
db.so.insert(
{
    "_id" : ObjectId("51ee899ec15d5aaff39d3353"),
    "first" : "first",
    "last" : "last",
    "email" : "email",
    "phone" : "555 555 5555",
    "userRole" : "su",
    "cards" : [
            {
                    "rfid_id" : ObjectId("51ee899ec15d5aaff39d3359")
            }
    ],
    "zones" : [
            {
                    "zone_id" : ObjectId("51ee899ec15d5aaff39d3357")
            }
    ]
});

db.so.update({}, {$pull:{ "cards": {"rfid_id": ObjectId("51ee899ec15d5aaff39d3359")}}}, false, false)
db.so.find().pretty();

Outputs:

{
    "_id" : ObjectId("51ee899ec15d5aaff39d3353"),
    "cards" : [ ],
    "email" : "email",
    "first" : "first",
    "last" : "last",
    "phone" : "555 555 5555",
    "userRole" : "su",
    "zones" : [
        {
            "zone_id" : ObjectId("51ee899ec15d5aaff39d3357")
        }
    ]
}

Although I did have to change the ObjectID for the pull slightly, as it was originally using a different string between your simple and full versions of the document.

Upvotes: 3

Related Questions