.
Suppose we have a collection named "users" that contains documents with the following fields:
_id: ObjectIdname: stringage: integercity: stringgender: stringscore: integer
We want to find the average score of users by city, sorted in descending order. We can use the following aggregation pipeline:
db.users.aggregate([
{
$group: {
_id: "$city",
average_score: { $avg: "$score" }
}
},
{
$sort: {
average_score: -1
}
])
Print down a stage in curly brackets, which will help to output 3 records only for cities with the highest average score.