MongoDB sort Stage

The $sort stage orders documents flowing through the pipeline according to one or more fields, either ascending or descending.

Sorting on a Single Field

$sort takes a document whose keys are field names and whose values indicate direction: 1 for ascending, -1 for descending. It reorders the entire set of documents currently in the pipeline before passing them to the next stage, and it works on both raw collection fields and fields that were computed earlier in the pipeline by stages like $project or $group.

Ascending and Descending Sorts

db.products.aggregate([
  { $sort: { price: 1 } }
])

Sorting on Multiple Fields

When you provide multiple keys, MongoDB sorts by the first key and uses subsequent keys only to break ties. This mirrors how ORDER BY works with multiple columns in SQL: the first field determines the primary order, and every following field only matters when earlier fields are equal.

Multi-Key Sort with Tie-Breaking

db.employees.aggregate([
  { $sort: { department: 1, salary: -1 } }
])

This groups employees by department alphabetically, and within each department orders them from highest to lowest salary. Field order in the sort document is significant; swapping the two keys would change the meaning entirely.

Sorting After Computed Fields

Sorting on a Grouped Aggregate

db.sales.aggregate([
  { $group: {
      _id: "$category",
      totalUnits: { $sum: "$units" }
  } },
  { $sort: { totalUnits: -1 } },
  { $limit: 10 }
])
  • 1 sorts a field in ascending order, from lowest to highest
  • -1 sorts a field in descending order, from highest to lowest
  • Multiple fields resolve ties left to right
  • $sort can reference fields introduced earlier by $group or $project
  • Placing $sort near an index-covered field early in a pipeline can avoid an expensive in-memory sort
Pipeline OrderBehavior
$sort before $groupSorts raw documents; group order is not guaranteed to preserve it
$sort after $groupSorts the computed group results directly, the common top-N pattern
$sort before $limitProduces a deterministic top-N or bottom-N result
Note: MongoDB has a 100 megabyte limit on the memory a single sort stage can use. For larger sorts, add { allowDiskUse: true } as an option to aggregate() so MongoDB can spill to temporary files on disk.
Note: If a $sort stage is the very first stage in your pipeline and the sort field is indexed, MongoDB can use the index to avoid sorting in memory altogether.