Aggregation pipeline with $limit

Report a typo

.

Suppose we have a collection named "users" that contains documents with the following fields:

  • _id: ObjectId
  • name: string
  • age: integer
  • city: string
  • gender: string
  • score: 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.

Enter a short text
___

Create a free account to access the full topic