$sort (Sort)
Last updated: 2026-10-09
$sort (Sort)
$sort orders pipeline documents by specified fields: 1 ascending, -1 descending, with multi-field sorts supported. Place it near the end, since intermediate stages may reorder documents. To sort with an index, put $match first. Large sorts exceed the default 100MB memory limit and fail unless allowDiskUse is enabled.
| Category | Core Stages |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $sort: { <field1>: <1 or -1>, <field2>: <1 or -1> } }
⚙️ Parameters
| sort key | Field names mapped to 1 (ascending) or -1 (descending); multiple fields compare in written order. |
|---|
Returns:Sorted document stream
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $sort: highest score first, name ascending on ties
db.scores.aggregate([
{ $sort: { score: -1, name: 1 } }
])
Output:
{ "name": "Alice", "score": 98 }
{ "name": "Bob", "score": 92 }
📌 Notes
- Multi-field sorts compare fields in written order
- Sorting over 100MB fails unless allowDiskUse is enabled
- Follow $sort with $limit to build top-N queries
🏷️ Related Tags
💡 Related Cases
Advanced Aggregation Pipelines: Complex Expressions and Transformations
Introduction to Aggregate Pipelines: The `aggregate` Method and the Basic Stage
$facet + $bucket + Text/Geospatial Search
$lookup and Associations with Multiple Sets
📚 Related Tutorials
❓ FAQ
QHow does $sort handle multiple fields?
AFields compare in written order: first by the first field, then by the second when values tie.
QCan $sort use an index?
AWhen the sort key matches an index and the stage is first or follows $match, the index avoids an in-memory sort.
QWhat if $sort hits the memory limit?
APass allowDiskUse: true in the aggregate options to spill to disk.