liveBook · Manning

$sort

As explained in MongoDB 8.0 in Action, Third Edition

$sort is an aggregation pipeline stage that orders documents according to specified field values.

$sort orders documents within an aggregation pipeline by one or more fields, in ascending or descending order. It supports practical tasks such as ranking grouped results for analysis or presentation while leaving the source collection unchanged unless the pipeline writes through $merge or $out. section 6.1.1 section 6.6

Use $sort effectively by combining it with other pipeline stages:

  • Place $match early to reduce the documents that later stages, including sorting, must process. section 6.1.2
  • Index fields used for sorting to speed execution and help prevent performance bottlenecks. section 6.1.2
  • Apply $limit when only the highest- or lowest-ranked results are needed, reducing memory use and execution time. section 6.1.1 section 6.1.2

Rank airports by route count

After filtering routes for airplane type "CR2" and grouping by source airport, use { $sort: { totalRoutes: -1 } } to rank airports by descending route count. Follow it with { $limit: 5 } to return only the five busiest airports. section 6.1.1

Listing 6.1 Executing an aggregation pipeline
db.routes.aggregate([
  {
    $match: { airplane: "CR2" } // Filter documents where the
➥airplane is "CR2"
  },
  {
    $group: {
      _id: "$src_airport",       // Group by source airport
      totalRoutes: { $sum: 1 }   // Count the number of routes
➥from each source
    }
  },
  {
    $sort: { totalRoutes: -1 }   // Sort the results by the
➥number of routes in descending order
  },
  {
    $limit: 5                    // Limit the number of displayed
➥documents to 5
  }
])


[
  { _id: 'DME', totalRoutes: 19 },
  { _id: 'SVX', totalRoutes: 17 },
  { _id: 'OVB', totalRoutes: 12 },
  { _id: 'LED', totalRoutes: 11 },
  { _id: 'OMS', totalRoutes: 8 }
]

Inspect the complete executable pipeline showing $match, $group, $sort, and $limit together with sample output. section 6.1.1

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines ascending and descending ordering and gives a worked pipeline, while emphasizing indexes and stage placement rather than sort internals.
Examples
Demonstrates ranking source airports by counted CR2 routes and returning the five airports with the most routes.
What it assumes
Assumes familiarity with aggregation pipelines and introduces $sort alongside filtering, grouping, and limiting stages.
What you can do after
Apply it via db.collection.aggregate() to order pipeline results and combine ranking with filtering, grouping, and limiting.
How it connects
Connects $sort with aggregation pipelines, $match, $group, $limit, indexes, and the aggregation framework.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.