{
A: "number"
}
How to write a MongoDB aggregation pipeline that returns both:
- the list of documents where
A > 100
- 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"
}
}
}
]
}
}
])