$match
$match filters documents in a pipeline using the same query syntax as find.
In this page:
Syntax
{ $match: { field: value } }
$match
$match keeps only the documents that satisfy its query and passes them on. It uses regular query operators.
At the start of a pipeline it can use indexes, so place it first whenever possible.
It cannot use aggregation expressions unless wrapped in $expr.
Note:
An early $match is the cheapest performance win in a pipeline.
Example: $match
test> db.orders.insertMany([
... { _id: 1, status: "paid", total: 50 }, { _id: 2, status: "open", total: 20 },
... { _id: 3, status: "paid", total: 80 }, { _id: 4, status: "cancelled", total: 15 }
... ])
{
acknowledged: true,
insertedIds: { '0': 1, '1': 2, '2': 3, '3': 4 }
}
test> db.orders.aggregate([{ $match: { status: "paid", total: { $gt: 60 } } }])
[ { _id: 3, status: 'paid', total: 80 } ]
test> db.orders.aggregate([{ $match: { status: { $in: ["open", "cancelled"] } } }, { $count: "n" }])
[ { n: 2 } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using $match late
- Using aggregation expressions without $expr
- Forgetting fields are case sensitive
Chapter Summary
- $match uses query syntax
- Best placed first
- Can use indexes at the start
- Use $expr for expressions
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: