You can remove nested document(s) in a specific MongoDB document using the $pull
operator (which will remove all nested documents in an array that match a specified condition). For example, let's suppose you have the following MongoDB collection:
[ { "_id": ObjectId("5a934e000102030405000000"), "name": "John Doe", "addresses": [ { "street": "456 Ave", "city": "london", "country": "UK" }, { "street": "123 Ave", "city": "nyc", "country": "US" }, { "street": "221B Baker St.", "city": "london", "country": "UK" }, ] }, { "_id": ObjectId("5a934e000102030405000001"), "name": "Jane Roe", "addresses": [ { "street": "742 Evergreen Terrace", "city": "springfield", "country": "US" } ] } ]
To delete, for example, all "addresses
" with { "city": "london" }
in a specific document, you can use the $pull
operator in the following way:
db.collection.update( { "_id": ObjectId("5a934e000102030405000000") }, { $pull: { "addresses": { "city": "london" } } } );
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.