TExcelTAD
Home › MongoDB › Aggregation $sort

Aggregation $sort

$sort orders the documents flowing through the pipeline. It takes a document of fields with 1 (ascending) or -1 (descending):

js
{ $sort: { field1: -1, field2: 1 } }

Sorting by one field

mongosh · try it yourself
db.customers.aggregate([
  { $sort: { joined: -1 } },
  { $limit: 4 },
  { $project: { _id: 0, name: 1, joined: 1 } }
]).forEach(c => print(c.joined.toISOString().slice(0, 10), c.name));
2026-05-19 Radia Perlman
2026-05-05 Edsger Dijkstra
2026-04-22 Katherine Johnson
2026-04-01 Hedy Lamarr

Sorting computed values

The big advantage over cursor.sort() is that you can sort on fields that a previous stage computed. Here customers are ranked by how much they have spent:

mongosh · try it yourself
print(db.orders.aggregate([
  { $match: { status: { $ne: 'cancelled' } } },
  { $group: { _id: '$customerId', spent: { $sum: '$total' }, orders: { $sum: 1 } } },
  { $sort: { spent: -1, _id: 1 } }
]).toArray());
[
  { _id: 5, spent: 209, orders: 3 },
  { _id: 3, spent: 178, orders: 3 },
  { _id: 1, spent: 142.5, orders: 3 },
  { _id: 11, spent: 131, orders: 2 },
  { _id: 7, spent: 121, orders: 1 },
  { _id: 2, spent: 55.5, orders: 2 },
  { _id: 9, spent: 48.5, orders: 2 },
  { _id: 10, spent: 45.5, orders: 1 },
  { _id: 6, spent: 34.5, orders: 1 }
]

Ties and stable results

When two documents have the same sort value, their relative order is not defined, and it may change between runs or server versions. Add a unique field as the last key:

mongosh · try it yourself
// three products are rated 4.8 or above; two of them tie at 4.8
print(db.products.aggregate([
  { $match: { rating: { $gte: 4.8 } } },
  { $sort: { rating: -1, name: 1 } },
  { $project: { _id: 0, name: 1, rating: 1 } }
]).toArray());
[
  { name: 'Ethiopia Yirgacheffe', rating: 4.9 },
  { name: 'Dark Chocolate Bar', rating: 4.8 },
  { name: 'Pour-Over Dripper', rating: 4.8 }
]

How values of different types sort

A field can hold different types in different documents. MongoDB then uses a fixed type order: MinKey < null (and missing) < numbers < strings < objects < arrays < ObjectId < booleans < dates < MaxKey. Missing fields sort like null, so with an ascending sort they come first:

mongosh · try it yourself
print(db.customers.aggregate([
  { $sort: { email: 1, _id: 1 } },
  { $limit: 4 },
  { $project: { _id: 0, name: 1, email: 1 } }
]).toArray());
[
  { name: 'Linus Torvalds' },
  { name: 'Donald Knuth' },
  { name: 'Radia Perlman' },
  { name: 'Ada Lovelace', email: 'ada@example.com' }
]

Case-sensitive strings and collation

Strings sort by their binary (UTF-8) value by default, so every uppercase letter comes before every lowercase one. A collation sorts the way people expect:

mongosh · try it yourself
db.words.insertMany([{ _id: 1, w: 'banana' }, { _id: 2, w: 'Apple' }, { _id: 3, w: 'cherry' }, { _id: 4, w: 'Date' }]);
const pipeline = [{ $sort: { w: 1 } }];
print(db.words.aggregate(pipeline).toArray().map(d => d.w));
print(db.words.aggregate(pipeline, { collation: { locale: 'en' } }).toArray().map(d => d.w));
[ 'Apple', 'Date', 'banana', 'cherry' ]
[ 'Apple', 'banana', 'cherry', 'Date' ]

Memory limits

A $sort that can't use an index holds documents in memory. Each blocking stage may use up to 100 MB; beyond that MongoDB writes temporary files to disk, which it does automatically since version 6.0 (allowDiskUse is on by default). A $sort at the very start of a pipeline can use an index instead, and a $sort followed by $limit only keeps the top documents.

Test yourself

With { $sort: { email: 1 } }, where do documents without an email field appear?

  1. Last
  2. First
  3. They are removed
  4. In random positions

Which list is sorted with the default (binary) string order?

  1. Apple, banana, cherry, Date
  2. Apple, Date, banana, cherry
  3. banana, cherry, Apple, Date
  4. Date, cherry, banana, Apple