How to Sort Results in MongoDB: Syntax and Examples
In MongoDB, you sort query results using the
sort() method, which takes an object specifying fields and sort order (1 for ascending, -1 for descending). For example, .sort({ age: 1 }) sorts documents by the age field in ascending order.Syntax
The sort() method is used after a find() query to order the results. It takes an object where keys are field names and values are 1 for ascending or -1 for descending order.
- field: The document field to sort by.
- 1: Sort ascending (smallest to largest).
- -1: Sort descending (largest to smallest).
mongodb
db.collection.find(query).sort({ field1: 1, field2: -1 })Example
This example shows how to sort a collection of users by their age in ascending order and then by name in descending order.
mongodb
db.users.find().sort({ age: 1, name: -1 })Output
[
{ "name": "Bob", "age": 25 },
{ "name": "Alice", "age": 25 },
{ "name": "Charlie", "age": 30 }
]
Common Pitfalls
Common mistakes when sorting in MongoDB include:
- Using values other than
1or-1for sort order, which will be ignored or cause errors. - Forgetting to chain
sort()afterfind(), which means sorting won't apply. - Sorting on fields that do not exist in documents, which returns results but may not be ordered as expected.
mongodb
/* Wrong: Using 0 instead of 1 or -1 */ db.users.find().sort({ age: 0 }) /* Right: Use 1 or -1 */ db.users.find().sort({ age: 1 })
Quick Reference
| Usage | Description |
|---|---|
| { field: 1 } | Sort by field ascending |
| { field: -1 } | Sort by field descending |
| { field1: 1, field2: -1 } | Sort by field1 ascending, then field2 descending |
| Use after find() | Apply sorting to query results |
Key Takeaways
Use the sort() method with { field: 1 } for ascending or { field: -1 } for descending order.
Always chain sort() after find() to apply sorting to query results.
Sorting on non-existing fields returns results but may not be ordered as expected.
Only use 1 or -1 as sort values; other values are invalid.
You can sort by multiple fields by including them in the sort object.