John Tiggernaught
John Tiggernaught

Reputation: 798

How to remove an array element from a Sub-Subdocument

I have a document with the following layout:

{
    "A1" : {
        "B1" : {
            "C1" : [ 
                ObjectId("123"),
                ObjectId("456")
            ],
            "C2" : [ 
                ObjectId("789"),
                ObjectId("abc")
            ]
        },
        "B2" : {
            "C1" : [ 
                ObjectId("def"),
                ObjectId("hij")
            ],
            "C2" : [ 
                ObjectId("klm"),
                ObjectId("nop")
            ]
        }
    }
}

I'd like to delete one of the array elements from A1.B1.C1 using their ID.

I'm using the following update code:

{
    "A1" : {
        "B1" : {
            "$pull" : {
                "C1" : "123"
            }
        }
    }
}

But that results in the following:

{
    "A1" : {
        "B1" : {}
    }
}

I've tried different variations of the update code, for example:

{
    "A1" : {
        "B1" : {
            "C1" : {
                "$pull" : "123"
            }
        }
    }
}

But that results in the following error:

Cast to [ObjectId] failed for value "[{"$pull":"123"}]"

Could someone provide some guidance as on how to remove a specific array element from a sub-sub-document?

Upvotes: 0

Views: 25

Answers (1)

Akrion
Akrion

Reputation: 18525

Have you tried:

"$pull" : {
   "A1.B1.C1" : mongoose.Types.ObjectId("123")
}

Should work.

Upvotes: 1

Related Questions