sort() (Sort Results)
Last updated: 2026-10-09
sort() (Sort Results)
sort() orders cursor results by given fields: `db.users.find().sort({ age: 1, name: -1 })`. Values are 1 for ascending, -1 for descending, applied field by field. Sorting runs server-side — fastest when backed by an index; unsorted-by-index cases sort in memory and can hit the 100MB cap.
| Category | Cursor |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
db.<collection>.find(<filter>).sort(<sortKey>)
⚙️ Parameters
| sort key | Field-to-direction mapping, e.g. {age: 1, name: -1}. |
|---|
Returns:The cursor sorted by the sort key (chainable).
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// sort: age ascending then name descending, take 3
const result = db.users.find()
.sort({ age: 1, name: -1 })
.limit(3)
.toArray()
result
Output:
[
{ _id: ObjectId('64c8a1b20000000000000001'), name: 'Alice', age: 21 },
{ _id: ObjectId('64c8a1b20000000000000002'), name: 'Bob', age: 25 }
]
📌 Notes
- 1 is ascending, -1 descending; multiple fields apply left to right
- Index-backed sorts perform best
- Indexless sorts over the 100MB memory cap error; allowDiskUse() helps
🏷️ Related Tags
💡 Related Cases
📚 Related Tutorials
❓ FAQ
QWhat do 1 and -1 mean in sort?
A1 is ascending, -1 descending — {age: -1} sorts oldest first.
QHow do I sort by multiple fields?
APass several fields in the sort key, e.g. {age: 1, name: -1} — age first, then name.
QWhat if my sort is slow?
AAdd a compound index on the sort fields; indexless sorts use memory, and allowDiskUse() helps with huge results.