Search code examples
mongodbprojection

Exclude nested documents based on a condition


I have a document in the following form

{
  "_id": "5c9a53b348a0ac000140b5f9",
  "e": [
    {
      "_id": "d6c74cd5-5808-4b0c-b857-57ddbcc72ce5",
      "isDeleted": true
    },
    {
      "_id": "d6c74cd5-5808-4b0c-b857-57ddbcc72ce6",
      "isDeleted": false
    }
  ]
}

Every document has a list of elements on it, each of the elements which may or may not be deleted. By default, I don't want to return the deleted data. Right now, I filter them server-side but that still means a lot of data gets transmitted unnecessarily. Is it possible to exclude this data on the database?

I've looked at $elemMatch but that only returns a single value so it doesn't look like the right tool for the job.

Is there a way to project a document with an array of nested documents to only include those subdocuments that adhere to a certain condition?


Solution

  • You can use $filter aggregation here

    db.collection.aggregate([
      { "$addFields": {
        "e": {
          "$filter": {
            "input": "$e"
            "cond": { "$eq": ["$$this.isDeleted", true] }
          }
        }
      }}
    ])