sort()
sort orders results ascending with 1 or descending with -1, and can use several fields.
In this page:
Syntax
db.collection_name.find(filter).sort({ field: 1 })
db.collection_name.find(filter).sort({ field1: -1, field2: 1 })
sort()
cursor.sort({ field: 1 }) sorts ascending and -1 descending. List several fields to break ties in order. Sorting without an index on large data can be slow or hit the memory limit, so index the sort fields you query often.
Note:
Sort keys order matters: { a: 1, b: -1 } sorts by a then b.
Example: sort()
test> db.players.insertMany([
... { _id: 1, name: "Ada", team: "red", score: 30 }, { _id: 2, name: "Bob", team: "blue", score: 50 },
... { _id: 3, name: "Cy", team: "red", score: 50 }, { _id: 4, name: "Di", team: "blue", score: 10 }
... ])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.players.find({}, { _id: 0 }).sort({ score: -1, name: 1 })
[
{ name: 'Bob', team: 'blue', score: 50 },
{ name: 'Cy', team: 'red', score: 50 },
{ name: 'Ada', team: 'red', score: 30 },
{ name: 'Di', team: 'blue', score: 10 }
]
test> db.players.find({}, { name: 1, _id: 0 }).sort({ score: -1 }).limit(2)
[ { name: 'Bob' }, { name: 'Cy' } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using asc or desc strings
- Forgetting sort with limit for top-N
- Sorting large collections without an index
Chapter Summary
- 1 ascending, -1 descending
- Multiple keys break ties
- Index sort fields
- Combine with limit for top-N
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: