← Back to MongoDB Course | Chapter 7: Aggregation | Lesson 2 of 7

$match

$match filters documents in a pipeline using the same query syntax as find.

In this page:

  1. $match
Syntax
javascript
{ $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

bash
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
  1. Using $match late
  2. Using aggregation expressions without $expr
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.