MongoDB Aggregation $limit
Introduction
The $limit
stage in MongoDB's aggregation framework is used to restrict the number of documents passed to the next stage in the pipeline. This is particularly useful when you only want to retrieve a subset of documents, such as the top results based on certain criteria.
Prerequisites
MongoDB installed and running on your machine.
Access to
mongosh
and a populated database with sample data.
Step 1: Start mongosh
mongosh
Open Terminal/Command Prompt:
Launch your terminal (macOS/Linux) or command prompt (Windows).
Start
mongosh
:Type the following command and press Enter:
Step 2: Switch to the Database
Switch to the database where your collection is located.
Use a Database:
Step 3: Sample Data
Let’s assume you have a collection named sales
with documents that look like this:
Step 4: Using $limit
$limit
1. Basic Usage of $limit
$limit
To limit the number of documents returned in the aggregation pipeline, you can use the $limit
stage.
For example, to retrieve only the first three documents from the sales
collection:
Output:
2. Using $limit
After Sorting
$limit
After SortingIt is common to use $limit
after sorting the results to get the top N documents based on a specific field. For example, if you want the top two items with the highest quantity sold:
Output:
3. Combining $limit
with Other Stages
$limit
with Other StagesYou can combine $limit
with other stages like $match
and $group
. For instance, if you want to find the top items sold, but only for those with a price greater than 1:
Output:
Conclusion
You have learned how to use the $limit
stage in MongoDB's aggregation framework to restrict the number of documents returned in a query. By combining $limit
with other stages like $sort
and $match
, you can refine your queries to retrieve specific subsets of data.
Feel free to reach out if you have any questions or need further guidance!
Last updated