user15375190
user15375190

Reputation:

How to pull an element in sub of sub array in MongoDB?

I want to pull an object from com_address where "add_id":111:

{
    "_id" : ObjectId("5f7b6b4e327e2111883909f3"),
    "FirstName" : "abc",
    "LastName" : "abc",
    "DateOfBirth" : "05/09/2020",
    "gender" : "M",
    "address" : {
        "country" : "string",
        "state" : "string",
        "city" : [ 
            {
                "id" : 15,
                "type" : "string",
                "com_address" : [ 
                    {
                        "add_id" : 113,
                        "street" : "string",
                        "house_no" : "string",
                        "landmark" : "string"
                    }, 
                    {
                        "add_id" : 114,
                        "street" : "string",
                        "house_no" : "string",
                        "landmark" : "string"
                    }
                ]
            }, 
            {
                "id" : 16,
                "type" : "string",
                "com_address" : [ 
                    {
                        "add_id" : 110,
                        "street" : "string",
                        "house_no" : "string",
                        "landmark" : "string"
                    }, 
                    {
                        "add_id" : 111,
                        "street" : "string",
                        "house_no" : "string",
                        "landmark" : "string"
                    }
                ]
            }
        ]
    }
}

This is my query: db.getCollection('student').update({"_id" : ObjectId("5f7b6b4e327e2111883909f3")},{$pull:{"address.city":{"com_address.add_id":111}}})

By doing this object inside city with id 16 is getting deleted instead of pulling an object from com_address.

How to pull an object from com_address with add_id?

Upvotes: 0

Views: 111

Answers (1)

Montgomery Watts
Montgomery Watts

Reputation: 4034

Try this, which uses the $[] operator

db.getCollection('student').update({
    "_id" : ObjectId("5f7b6b4e327e2111883909f3")
},
{
    $pull: { "address.city.$[].com_address": { "add_id": 111 }}
})

Upvotes: 1

Related Questions