liveBook · Manning

$limit

As explained in MongoDB 8.0 in Action, Third Edition

$limit is an aggregation pipeline stage that restricts the number of documents passed to later stages or returned by the pipeline.

$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

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Defines the stage’s pipeline role and performance benefit, but does not detail internal execution mechanics.
Examples
Demonstrates a CR2 routes aggregation that returns the five source airports with the most routes.
What it assumes
Uses aggregation pipeline stages such as filtering, grouping, and sorting.
What you can do after
Apply it via MongoDB's db.collection.aggregate() method to cap pipeline results.
How it connects
Connects $limit with aggregation pipelines, $match, $group, and $sort.

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.