0
0
MongodbHow-ToBeginner · 3 min read

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 by field. Use 1 for ascending and -1 for descending order.
  • .limit(n) restricts the output to n documents.
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() before sort() which can lead to incorrect results because limit() restricts documents before sorting.
  • Not specifying the sort order correctly (use 1 for ascending, -1 for 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

MethodDescriptionExample
find()Retrieve documents from a collectiondb.collection.find({})
sort()Sort documents by field(s)db.collection.find().sort({ age: 1 })
limit()Limit number of documents returneddb.collection.find().limit(5)
CombinedSort then limit resultsdb.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.