$limit is an aggregation pipeline stage that caps the number of documents passed to later stages or returned to the client. Limiting results can reduce memory use and improve execution time, especially with large data sets. section 6.1.1 section 6.1.2
Selecting the five busiest source airports
A routes pipeline can match CR2 aircraft, group routes by source airport, sort the groups by descending route count, and apply { $limit: 5 } to return only the five busiest airports. The example produces DME, SVX, OVB, LED, and OMS. section 6.1.1
Listing 6.1 Executing an aggregation pipeline
db.routes.aggregate([
{
$match: { airplane: "CR2" } // Filter documents where the
➥airplane is "CR2"
},
{
$group: {
_id: "$src_airport", // Group by source airport
totalRoutes: { $sum: 1 } // Count the number of routes
➥from each source
}
},
{
$sort: { totalRoutes: -1 } // Sort the results by the
➥number of routes in descending order
},
{
$limit: 5 // Limit the number of displayed
➥documents to 5
}
])
[
{ _id: 'DME', totalRoutes: 19 },
{ _id: 'SVX', totalRoutes: 17 },
{ _id: 'OVB', totalRoutes: 12 },
{ _id: 'LED', totalRoutes: 11 },
{ _id: 'OMS', totalRoutes: 8 }
]
Use the complete aggregation example to inspect how $limit follows filtering, grouping, and sorting in an executable MongoDB pipeline. section 6.1.1
Apply $limit with these practical considerations:
- Place it where the pipeline should stop forwarding documents; placing it after $sort supports top-N results such as the five highest route counts. section 6.1.1
- Combine it with an early $match when possible so later processing handles fewer documents. section 6.1.2
