Jaskaran singh Rajal
Jaskaran singh Rajal

Reputation: 2330

remove embedded document from mongo db $pull is not working

I have embedded document in mongodb how can I remove only one address where pincode : 140901 and update where pincode is : 152364

db.add_fun.insert({
"_id" : ObjectId("5a82e6dc1139b572569fa785"),
"name" : "Vikas",
"salary" : 72.0,
"address" : [ 
    {
        "address_id" : ObjectId("5a82f0e51139b572569fa78c"),
        "address" : "Mullanpur ",
        "pincode" : "140901",
        "country" : "India"
    }, 
    {
        "address_id" : ObjectId("5a82f0e51139b572569fa78d"),
        "address" : "mohali ",
        "pincode" : "152364",
        "country" : "India"
    }
]
})

I try this but not working

db.add_fun.update({},
        {
            $pull: {
                        address: {
                            $elemMatch: {
                                pincode: "140901"
                            }
                        }
            }
        },
        {
            multi:true
        }
    )

want to remove this

{
"address_id" : ObjectId("5a82f0e51139b572569fa78c"),
"address" : "Mullanpur ",
"pincode" : "140901",
"country" : "India"
}, 

and want this result

{
    "_id" : ObjectId("5a82e6dc1139b572569fa785"),
    "name" : "Vikas",
    "salary" : 72.0,
    "address" : [ 

        {
            "address_id" : ObjectId("5a82f0e51139b572569fa78d"),
            "address" : "mohali ",
            "pincode" : "152364",
            "country" : "India"
        }
    ]
}

Upvotes: 5

Views: 255

Answers (3)

Alejandro Galera
Alejandro Galera

Reputation: 3691

Please, let me recommend you remove objects by ObjectId to guarantee uniqueness.

db.add_fun.update(
    { },
    { $pull: {
        address: {
            "address_id" : ObjectId("5a82f0e51139b572569fa78c")
        }    
     } },
    { multi:true }
);

Upvotes: 0

Kevin Smith
Kevin Smith

Reputation: 14436

Just add a query on the address field to make sure you're only updating arrays:

db.add_fun.update(
    { address: { $type: 4 }},
    { $pull: {
        address: {
            pincode: "140901"
        }    
     } },
    { multi:true }
);

Upvotes: 0

Alex Blex
Alex Blex

Reputation: 37018

No need for $elemMAtch, just a condition for the sub-documents within array. In your case:

db.add_fun.update(
{},
{ $pull: {
    address: {
        pincode: "140901"
    }    
} },
{ multi:true }
);

Docs: https://docs.mongodb.com/manual/reference/operator/update/pull/

Upvotes: 3

Related Questions