How to Remove Array Elements in a Specific MongoDB Document?

Find out how to delete nested documents in a child array of a MongoDB document

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" } }
  }
);

Hope you found this post useful. It was published . Please show your love and support by sharing this post.