liveBook · Manning

Sorting algorithm

As explained in MongoDB 8.0 in Action, Third Edition

Sorting is the ordering of query results according to one or more document fields.

In MongoDB, sort orders query results by one or more document fields. Use it to present results in a meaningful order; combine it with skip and limit when navigating large result sets. section 4.10.1 section 4.10

Order routes by stops

Run db.routes.find().sort({ stops: -1 }) to list routes by number of stops in descending order. Use 1 instead of -1 for ascending order. section 4.10.1

For multi-field sorts, align the query with a compound index:

  • Create db.movies.createIndex({ runtime: 1, year: 1 }), then run db.movies.find().sort({ runtime: 1, year: 1 }). The sort orders first by runtime, then by year. section 7.6.7
  • Keep sort fields in index order. An index on { a: 1, b: 1 } supports sorting by { a: 1, b: 1 }, but not by { b: 1, a: 1 }. section 7.6.7

Filter and sort movies

After creating the runtime-and-year index, run db.movies.find({ runtime: { $gt: 40 } }).sort({ runtime: 1, year: 1 }) to filter by runtime and order the matching movies by both fields. section 7.6.7

Figure 7.3 The explain plan for a query optimized with an index using the ESR rule in Compass. The plan contains an IXSCAN stage, which uses the year_1_title_1_imdb.rating_1 index to scan and fetch documents. This stage returned two documents and examined four index keys with an execution time of 0 ms. Then the FETCH stage retrieves the documents with an execution time of 0 ms. (Image © MongoDB 2025)

An explain-plan example in MongoDB Compass shows an IXSCAN using a compound index for a movie query filtered by year and rating and sorted by title. Inspecting the plan connects the chosen field order to actual index use. section 7.2.2

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Demonstrates sort directions and compound-index field order, but does not develop sorting-algorithm internals.
Examples
Shows routes ordered by stops and movies ordered by runtime and year, including a filtered movie query.
What you can do after
Apply it via MongoDB find().sort() and configure a matching compound index for multi-field ordering.
How it connects
Connects sorting to the MongoDB Query API, pagination, compound indexes, index prefixes, and explain plans.

Also explained in

Compare how 18 books explain sorting algorithm →

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.