How to Use Sort with Limit in MongoDB: Simple Guide
In MongoDB, you can use
sort() to order documents by a field and limit() to restrict the number of results returned. Chain them together like db.collection.find().sort({field: 1}).limit(n) to get the top n sorted documents.Syntax
The basic syntax to sort and limit results in MongoDB is:
db.collection.find(query).sort({field: order})sorts documents byfield. Use1for ascending and-1for descending order..limit(n)restricts the output tondocuments.
mongodb
db.collection.find(query).sort({field: 1}).limit(n)Example
This example shows how to get the top 3 users sorted by their age in descending order:
mongodb
db.users.insertMany([
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 22 },
{ name: "David", age: 35 },
{ name: "Eve", age: 28 }
])
// Query to sort by age descending and limit to 3 results
const result = db.users.find().sort({ age: -1 }).limit(3).toArray()
printjson(result)Output
[
{ "_id": ObjectId("..."), "name": "David", "age": 35 },
{ "_id": ObjectId("..."), "name": "Bob", "age": 30 },
{ "_id": ObjectId("..."), "name": "Eve", "age": 28 }
]
Common Pitfalls
Common mistakes when using sort() with limit() include:
- Calling
limit()beforesort()which can lead to incorrect results becauselimit()restricts documents before sorting. - Not specifying the sort order correctly (use
1for ascending,-1for descending). - Forgetting to convert the cursor to an array or iterate it to see results.
mongodb
/* Wrong order: limit before sort */ db.users.find().limit(3).sort({ age: -1 }) /* Correct order: sort before limit */ db.users.find().sort({ age: -1 }).limit(3)
Quick Reference
| Method | Description | Example |
|---|---|---|
| find() | Retrieve documents from a collection | db.collection.find({}) |
| sort() | Sort documents by field(s) | db.collection.find().sort({ age: 1 }) |
| limit() | Limit number of documents returned | db.collection.find().limit(5) |
| Combined | Sort then limit results | db.collection.find().sort({ age: -1 }).limit(3) |
Key Takeaways
Always call
sort() before limit() to get correct sorted results.sort() takes an object with field names and 1 (asc) or -1 (desc) as values.limit(n) restricts the number of documents returned to n.Use
toArray() or iterate the cursor to see query results in code.Combining
sort() and limit() efficiently fetches top sorted documents.