How to Use $limit in Aggregation in MongoDB
In MongoDB aggregation, use the
$limit stage to restrict the number of documents passed to the next stage or returned. Place $limit in the pipeline with a positive integer to specify the maximum number of documents to keep.Syntax
The $limit stage takes a single positive integer that specifies the maximum number of documents to pass along in the aggregation pipeline.
{ $limit:: Limits the output to the first} numberdocuments.
json
{
$limit: <positive_integer>
}Example
This example shows how to use $limit to get only the first 3 documents from a collection named products during aggregation.
mongodb
db.products.aggregate([
{ $limit: 3 }
])Output
[
{ "_id": 1, "name": "Pen", "price": 1.5 },
{ "_id": 2, "name": "Notebook", "price": 3.0 },
{ "_id": 3, "name": "Eraser", "price": 0.5 }
]
Common Pitfalls
Common mistakes when using $limit include:
- Using a non-integer or negative number, which causes errors.
- Placing
$limittoo late in the pipeline, which may process unnecessary documents before limiting. - Confusing
$limitwith thelimit()method outside aggregation.
mongodb
/* Wrong: negative limit causes error */ db.collection.aggregate([{ $limit: -5 }]) /* Right: positive integer limit */ db.collection.aggregate([{ $limit: 5 }])
Quick Reference
| Stage | Description | Example |
|---|---|---|
| $limit | Limits the number of documents passed to the next stage | { $limit: 10 } |
| Usage | Use inside aggregation pipeline array | [{ $match: {...} }, { $limit: 5 }] |
| Value | Must be a positive integer | 5 |
Key Takeaways
Use $limit in aggregation to restrict the number of documents passed forward.
The value for $limit must be a positive integer.
Place $limit early in the pipeline to improve performance by reducing documents processed.
Do not confuse $limit stage with the find() method's limit() function.
Incorrect values like negative numbers cause errors in aggregation.