MongoDB Limit Documents
MongoDB Limit Documents – To limit the number of records that a query returns in the result, use the cursor.limit() method. The limit method accepts a number as an argument and returns at most that many documents from the cursor.
In this tutorial, we shall learn how to limit the number of records that a query returns in the result using examples. We shall also see how limit() behaves with no argument, how to combine it with sort(), and how it is used in pagination with skip().
MongoDB limit() method syntax for find() queries
The syntax of limit method is
cursor.limit(N)
Here, N is the maximum number of documents that should be returned from the cursor. For example, limit(5) returns at most five documents. If the query matches fewer than five documents, MongoDB returns only the matching documents.
When no value is provided, all the records are fetched, else the value provided in the argument would be considered.
Note : db.collection.find() returns cursor to the records. And limit() method can be applied on this cursor to limit the number of records as shown below :
db.collection.find().limit(N)
You can also apply limit() after a filter condition. In the following syntax, MongoDB first finds documents that match the condition and then returns only the specified number of documents from the cursor.
db.collection.find({ field: value }).limit(N)
Example 1 – Limit documents in a MongoDB query
In this example, we will limit the number of documents in the result by passing a number as argument to limit() method.
> db.people.find().limit(2)
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb2"), "name" : "Midhuna", "age" : 23, "place" : "Amaravati" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb3"), "name" : "Akhil", "age" : 24, "place" : "New York", "bonus" : 250 }
Only two documents, as provided to the limit method, are fetched in the result.
Example 2 – limit() method default operation in MongoDB
If no integer is provided as argument to limit() method, then it returns all the documents for the query.
> db.people.find().limit()
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb2"), "name" : "Midhuna", "age" : 23, "place" : "Amaravati" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb3"), "name" : "Akhil", "age" : 24, "place" : "New York", "bonus" : 250 }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb4"), "name" : "Honey", "age" : 27, "profession" : "Docter" }
{ "_id" : ObjectId("59eeba4e5f82df4555f2bfb5"), "name" : "Manju", "age" : 28, "place" : "Vizag", "profession" : "Driver" }
All documents are fetched in the result.
MongoDB limit() with a filter condition
Most real queries use limit() along with a filter. For example, the following query returns at most two documents from the people collection where age is greater than or equal to 24.
db.people.find({ age: { $gte: 24 } }).limit(2)
The important point is that limit() controls the number of documents returned to the client. It does not change the documents stored in the collection.
MongoDB sort() and limit() for top results
When you need the highest, lowest, latest, or oldest records, use sort() with limit(). Without sorting, the limited result should not be treated as a meaningful top-N result because the returned order is not usually the business order you want.
The following query returns the two oldest people by sorting age in descending order and then limiting the cursor to two documents.
db.people.find().sort({ age: -1 }).limit(2)
To return the two youngest people, sort age in ascending order.
db.people.find().sort({ age: 1 }).limit(2)
For larger collections, create indexes that support the filter and sort fields. This helps MongoDB avoid unnecessary scanning and sorting before returning the limited result.
MongoDB skip() and limit() for simple pagination
limit() is often used with skip() to show paginated results. For example, if each page shows two documents, page 1 can be fetched with limit(2).
db.people.find().sort({ _id: 1 }).limit(2)
Page 2 can be fetched by skipping the first two documents and then limiting the result to two documents.
db.people.find().sort({ _id: 1 }).skip(2).limit(2)
Always use a stable sort field for pagination. Sorting by _id is common for basic examples, but in an application you may sort by a created date, score, name, or another indexed field depending on the requirement.
MongoDB aggregation $limit stage
MongoDB also supports limiting documents inside an aggregation pipeline using the $limit stage. This is different from the cursor method limit(), but the purpose is similar: it passes only the specified number of documents to the next stage of the pipeline.
db.people.aggregate([
{ $match: { age: { $gte: 24 } } },
{ $sort: { age: -1 } },
{ $limit: 2 }
])
In aggregation, place $match and $sort before $limit when you need the top results from a filtered and sorted set. If you put $limit too early, later stages will process only that smaller subset.
MongoDB limit() values and common mistakes
- Using limit without sort for top results: Use
sort()beforelimit()when you need top, latest, oldest, highest, or lowest records. - Expecting limit to update documents:
limit()is for read results. It does not restrict update operations. - Using very large skip values for deep pages:
skip()with high offsets can become inefficient on large collections. For large applications, range-based pagination using an indexed field is usually better. - Forgetting indexes: If your query filters and sorts a large collection, an appropriate index is important before applying
limit(). - Confusing cursor limit with aggregation limit: Use
cursor.limit(N)withfind()queries and{ $limit: N }inside aggregation pipelines.
Quick checklist for MongoDB limit() queries
- Confirm the number passed to
limit()matches the page size or result size required by the application. - Add
sort()when the limited result must be deterministic or ordered by a business field. - Use a filter condition before
limit()when only a subset of documents is needed. - Check that the filter and sort fields are supported by suitable indexes for large collections.
- Use
$limitinstead oflimit()when the query is written as an aggregation pipeline.
FAQs on MongoDB limit documents
What does limit() do in MongoDB?
limit() restricts the number of documents returned by a MongoDB cursor. For example, db.people.find().limit(2) returns at most two documents from the people collection.
Does MongoDB limit() change documents in the collection?
No. limit() only controls the query result returned to the client. It does not insert, update, or delete documents in the collection.
Should I use sort() with limit() in MongoDB?
Use sort() with limit() when the order matters. For example, to get the oldest two people, sort by age in descending order and then apply limit(2).
How do I limit documents in a MongoDB aggregation pipeline?
Use the $limit stage inside the aggregation pipeline. For example, { $limit: 2 } passes only two documents to the next pipeline stage.
Can I use skip() and limit() together in MongoDB?
Yes. skip() and limit() are commonly used together for simple pagination. Use a stable sort() with them so that page results remain predictable.
Conclusion
In this MongoDB Tutorial – MongoDB Limit Documents, we have learnt to limit the number of documents returned in the result. Use db.collection.find().limit(N) for regular find queries, combine it with sort() when order matters, and use $limit when working inside an aggregation pipeline. In our next tutorial, we shall learn to skip first N documents of a query.
TutorialKart.com