Delete inline document from mongo db $ pull not working

I have a built-in document in mongodb, how can I delete only one address where pincode: 140901 and update where pincode: 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 work

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

want to delete this

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

and want to get this result

 { "_id" : ObjectId("5a82e6dc1139b572569fa785"), "name" : "Vikas", "salary" : 72.0, "address" : [ { "address_id" : ObjectId("5a82f0e51139b572569fa78d"), "address" : "mohali ", "pincode" : "152364", "country" : "India" } ] } 
+5
source share
2 answers

There is no need for $elemMAtch , just a condition for subdocuments inside an array. In your case:

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

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

+3
source

Just add the query to the address field to make sure that you are only updating the arrays:

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

Source: https://habr.com/ru/post/1275340/


All Articles