The $sort stage orders documents in your pipeline—ascending or descending by one or more fields—so top-N lists, leaderboards, and paginated APIs return predictable results.
01
1 / -1
Asc / desc.
02
Multi-key
Tie-breakers.
03
Top-N
With $limit.
04
Pagination
Before $skip.
05
Computed
After $set.
06
Indexes
Performance.
Fundamentals
Definition and Usage
$sort is an aggregation stage that rearranges documents by specified field(s). Each sort key uses 1 for ascending order or -1 for descending order. MongoDB compares fields left to right when multiple keys are listed.
Use $sort whenever order matters: recent-first feeds, leaderboard rankings, alphabetical directories, and the stable ordering required before $skip and $limit pagination.
Foundation
📝 Syntax
$sort accepts an object of field names mapped to sort direction:
Dan avgPerExam: 37.5
Faye avgPerExam: 23.75
(Page 2 would return Eli only)
How It Works
Production pipelines combine filter, computed fields, sort, and pagination. Sort must precede skip/limit so each page shows the correct slice of the ranked list.
Compare
📋 $sort vs related ordering tools
Tool / stage
What it orders
Best for
$sort
Full documents by field values
Leaderboards, feeds, pagination order
find().sort()
Query cursor results (non-aggregation)
Simple queries without pipeline
$sortByCount
Group counts descending by field value
Tag clouds, category frequency charts
$limit alone
First N in current order (no reorder)
Cap size—not ranked top-N
$geoNear
By distance from a point
Location proximity—not general sort
🧠 How $sort Works
1
Documents arrive
Input from collection or prior stages ($match, $set, etc.).
Input
2
Sort plan chosen
MongoDB uses an index if sort keys match, otherwise performs an in-memory (or disk-spill) sort.
$sort defines pipeline order: ascending with 1, descending with -1, multi-key for tie-breakers, and always before skip/limit when pages must be stable.
Next: $sortByCount—a specialized stage that groups, counts, and sorts category frequencies in one step.
Create indexes matching your most common $sort keys
Add a unique tie-breaker (e.g. _id or name) for stable pages
Combine $sort + $limit for top-N leaderboards
Filter with $match before sorting large collections
Sort computed fields after $set when ranking derived metrics
❌ Don’t
Rely on natural collection order—always sort explicitly
Put $skip before $sort when order matters
Sort huge result sets without indexes on busy production clusters
Confuse $sort with $sortByCount for general ordering
Forget allowDiskUse when sorts exceed memory on big batches
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about $sort
Use these points whenever pipeline order matters.
5
Core concepts
📈01
1 / -1
Asc / desc.
Basics
🔗02
Multi-key
Tie-break.
Pattern
🏆03
Top-N
+ $limit.
Rank
📄04
Before skip
Stable pages.
Pagination
⚡05
Index match
Fast sort.
Perf
❓ Frequently Asked Questions
$sort reorders documents in the aggregation pipeline by one or more fields. Use 1 for ascending (A→Z, low→high) and -1 for descending (Z→A, high→low). Sorted output flows to stages like $skip, $limit, or $group.
Yes, when you need meaningful pagination or top-N lists. Pattern: $match → $sort → $skip → $limit. Without $sort first, skip/limit operate on arbitrary order.
Yes. Add the field with $set or $addFields, then $sort on that computed field—e.g. lineTotal from $multiply before sorting by revenue.
When $sort is early in the pipeline and matches an index key order, MongoDB can use the index and avoid an in-memory sort. Otherwise it performs an in-memory sort subject to the 100 MB limit unless allowDiskUse is enabled.
$sort orders full documents by field values. $sortByCount groups by a field, counts each group, and returns sorted count summaries—it is a shortcut for group-plus-sort on counts, not general document sorting.
Did you know?
When $sort is the first stage and its keys match a collection index, MongoDB can return results in index order without a separate in-memory sort—often the biggest performance win for paginated APIs. Run explain() on your pipeline to see whether the plan says IXSCAN with no SORT stage. See the official $sort docs.