MongoDB limit Stage
The $limit stage truncates the pipeline's document stream to a maximum count, commonly used to implement top-N results or pagination.
How $limit Works
$limit takes a single positive integer and passes through at most that many documents from its input, discarding everything after that count. It does not filter based on content the way $match does; it simply cuts off the stream once the limit is reached, in whatever order the documents currently arrive in.
Basic Usage
db.products.aggregate([
{ $limit: 3 }
])Without an accompanying $sort, the three documents returned are whatever order the collection happens to yield them in, which is not guaranteed to be meaningful. In almost every real use case, $limit follows a $sort stage so the truncation reflects an actual ranking.
Pairing $limit with $sort
Top 5 Highest-Priced Products
db.products.aggregate([
{ $sort: { price: -1 } },
{ $limit: 5 }
])Placing $sort immediately before $limit is the standard pattern for a leaderboard, a top-N report, or a most-recent list. MongoDB can often optimize this pair together, especially when the sort field is indexed, avoiding a full in-memory sort of the entire collection.
Limit for Sampling and Debugging
Quickly Previewing a Pipeline's Shape
db.events.aggregate([
{ $match: { type: "click" } },
{ $project: { _id: 0, userId: 1, page: 1, timestamp: 1 } },
{ $limit: 10 }
])Adding a small $limit at the end of a pipeline you are still building is a handy way to preview the output shape without waiting for a full scan across a large collection to complete.