Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove embedded document from mongo db $pull is not working

Tags:

mongodb

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"
        }
    ]
}
like image 448
Jaskaran singh Rajal Avatar asked Oct 17 '22 22:10

Jaskaran singh Rajal


1 Answers

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/

like image 176
Alex Blex Avatar answered Oct 21 '22 08:10

Alex Blex