How to Use Limit in MongoDB: Syntax and Examples
In MongoDB, use the
limit() method to restrict the number of documents returned by a query. It takes a single number argument specifying the maximum results to return. For example, db.collection.find().limit(5) returns only 5 documents.Syntax
The limit() method is used after a find() query to specify the maximum number of documents to return.
db.collection.find(query).limit(number)queryis optional and filters documents.numberis the maximum count of documents to return.
mongodb
db.collection.find().limit(10)Example
This example shows how to get only 3 documents from the users collection.
mongodb
db.users.find().limit(3)Output
[
{ "_id": 1, "name": "Alice", "age": 25 },
{ "_id": 2, "name": "Bob", "age": 30 },
{ "_id": 3, "name": "Charlie", "age": 22 }
]
Common Pitfalls
One common mistake is forgetting to use limit() after find(), which returns all documents instead of a limited number.
Another is passing a non-integer or negative number to limit(), which will cause an error or unexpected results.
mongodb
/* Wrong: limit used before find */ db.collection.limit(5).find() /* Correct: limit used after find */ db.collection.find().limit(5)
Quick Reference
| Method | Description | Example |
|---|---|---|
| find() | Fetches documents from a collection | db.collection.find({ age: { $gt: 20 } }) |
| limit(n) | Limits the number of documents returned to n | db.collection.find().limit(5) |
| skip(n) | Skips the first n documents | db.collection.find().skip(10) |
| sort() | Sorts documents by a field | db.collection.find().sort({ age: 1 }) |
Key Takeaways
Use
limit(n) after find() to restrict query results to n documents.The argument to
limit() must be a positive integer.Without
limit(), queries return all matching documents.Always chain
limit() after find(), not before.Combine
limit() with skip() and sort() for effective pagination.