Skip to main content

$limit

The $limit stage in MongoDB's aggregation pipeline is used to limit the number of documents passed to the next stage in the pipeline. It provides a way to sample data and can be particularly useful for pagination, testing, or optimizing performance by reducing the amount of data that has to be processed in subsequent stages.

Basic Syntax

The basic syntax of the $limit stage is as follows:

db.collection.aggregate([
{
$limit: <number>
}
]);
  • <number>: The maximum number of documents to pass to the next stage. Must be a positive integer.

Examples

Simple Limit

To limit the output to 5 documents:

db.orders.aggregate([
{
$limit: 5
}
]);

Limit After Sorting

To sort documents by the amount field in descending order and then limit the output to the top 5:

db.orders.aggregate([
{
$sort: { amount: -1 }
},
{
$limit: 5
}
]);

Limit with Other Stages

You can use $limit in conjunction with other stages like $match, $group, and $project to perform more complex queries. For example, to filter documents where status is "A", group them by customer, and then limit the output to 3:

db.orders.aggregate([
{
$match: { status: "A" }
},
{
$group: { _id: "$customer", total: { $sum: "$amount" } }
},
{
$limit: 3
}
]);

Considerations

  1. Performance: Using $limit early in the pipeline can significantly improve the performance of subsequent stages by reducing the number of documents they have to process.

  2. Order of Stages: The placement of $limit in the pipeline matters. For example, placing $limit before $sort would sort only the limited documents, which may not give you the top or bottom documents you intended to find.

  3. No Guarantee on Order: Unless used with $sort, $limit does not guarantee any particular order of documents.