Lesson 19 +10 XP

$match and $limit

$match and $limit

$match filters documents (like find()), and $limit caps how many documents pass to the next stage.

$match - filter documents

db.listingsAndReviews.aggregate([
  { $match: { property_type: "House" } },
  { $limit: 2 },
  { $project: { name: 1, bedrooms: 1, price: 1 } }
])
  • $match uses the same query syntax as find() - operators like $gt and $in all work.
  • Put $match as early as possible in the pipeline. Filtering early means later stages process fewer documents, which speeds things up.

$limit - cap the number of documents

db.movies.aggregate([{ $limit: 1 }])
  • $limit takes a plain number.
  • It limits the number of documents passed to the next stage.
  • Usually combined with $sort - sort first, then limit to get a "top N".

The classic top-N pattern

db.listingsAndReviews.aggregate([
  { $sort: { accommodates: -1 } },
  { $project: { name: 1, accommodates: 1 } },
  { $limit: 5 }
])

TL;DR

  • $match filters; put it first for performance.
  • $limit caps documents to the next stage.
  • Sort then limit for "top N" results.