LAX_DEV
LAX_DEV

Reputation: 2281

MongoDB - $pull (remove an array element) from a nested document

I need to remove an array item from a nested document and the $pull is not working. I need to remove item from "data.tags" array.

This is my document

{
    "_id" : "TAGS",
    "data" : {
        "tags" : [ 
            {
                "_id" : ObjectId("5cff889688204e2cc6e219f7"),
                "tag" : "tag1"
            }, 
            {
                "_id" : ObjectId("5d00b888378f6584f25946f2"),
                "tag" : "tag2"
            }, 
            {
                "tag" : "tag3",
                "_id" : ObjectId("5d09cbf607bc04a8fa8dd2a9")
            }, 
            {
                "tag" : "tag2",
                "_id" : ObjectId("5d09cbfb07bc04a8fa8dd2aa")
            }
        ]
    }
}

and when I tried the update with pull it does NOT error but does not remove the item.

My update statement

.update({"_id" : "TAGS"}, {"$pull": { "data.tags": {"_id": "5d09cbf607bc04a8fa8dd2a9"}}})

Upvotes: 1

Views: 48

Answers (1)

Felipe Sulser
Felipe Sulser

Reputation: 1205

You are missing the ObjectId Constructor. Otherwise the types do not match as you are assuming that "_id" is of type string.

.update({"_id" : "TAGS"}, {"$pull": { "data.tags": {"_id": ObjectId("5d09cbf607bc04a8fa8dd2a9")}}})
                                                             ^^^

Upvotes: 2

Related Questions