Loading lessons...
$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 } }
])
$matchuses the same query syntax asfind()- operators like$gtand$inall work.- Put
$matchas 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 }])
$limittakes 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
$matchfilters; put it first for performance.$limitcaps documents to the next stage.- Sort then limit for "top N" results.