Skip to main content

What does the $sort stage do?

The $sort stage sorts the stream of documents inside the aggregation pipeline - by one or several fields, ascending (1) or descending (-1). Conceptually, this is the analog of ORDER BY in SQL.

How it works

  • receives documents from the previous stage
  • sorts them in memory or using temporary storage
  • passes the already-sorted stream further down the pipeline

Example

js
{ $sort: { createdAt: -1, price: 1 } }

First it sorts by createdAt descending, and where values match, by price ascending.

An important nuance

$sort works most efficiently after $match, once there's already less data. If the sorted fields are indexed (in a plain find), that speeds up sorting, but inside a pipeline, sorting more often happens in memory.

Summary

$sort is the stage that controls the order of documents, so the next stages (or the final result) get the data in the sequence you need.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

What does the $sort stage do?: MongoDB Interview Question