Home > database >  query that returns both aggregated data as well as filtered documents
query that returns both aggregated data as well as filtered documents

Time:12-26

{
  A: "number"
}

How to write a MongoDB aggregation pipeline that returns both:

  1. the list of documents where A > 100
  2. and the average of all the documents returned?

In other words, this query must return both the granular filtered documents and then a grouped statistic, which is the average.

CodePudding user response:

You can do it with $facet stage in the Aggregation pipeline:

db.collection.aggregate([
  {
    "$match": {
      "A": {
        "$gt": 100
      }
    }
  },
  {
    "$facet": {
      "list": [],
      "average": [
        {
          "$group": {
            "_id": null,
            "value": {
              "$avg": "$A"
            }
          }
        }
      ]
    }
  }
])

Working example

  • Related