$match (Filter Documents)
Last updated: 2026-10-09
$match (Filter Documents)
$match filters documents with a query condition, passing only matching documents to subsequent stages. It is the aggregation equivalent of find()'s query predicate. Place $match as early as possible — it can use indexes and reduces the document count entering later stages, making it the #1 aggregation performance rule.
| Category | Core Stages |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $match: { <query> } }
⚙️ Parameters
| query | Same query expression as find(), supporting comparison/logical/element operators. |
|---|
Returns:Filtered document stream (for the next stage)
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $match: only orders with status A
db.orders.aggregate([
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } }
])
Output:
// Returns total per customer
{ "_id": "A123", "total": 250 }
{ "_id": "B456", "total": 130 }
📌 Notes
- Place $match first to leverage indexes
- Cannot use $where or $text inside $match ($text must be the first stage)
- Index optimizations stop after the $match stage
🏷️ Related Tags
💡 Related Cases
Advanced Aggregation Pipelines: Complex Expressions and Transformations
Introduction to Aggregate Pipelines: The `aggregate` Method and the Basic Stage
Change Streams: Real-Time Change Monitoring
$facet + $bucket + Text/Geospatial Search
$lookup and Associations with Multiple Sets
Mongoose Models and Schema Design
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $match and find()?
AThe query conditions are identical, but $match is used inside an aggregation pipeline and passes results to the next stage.
QCan $match be placed in the middle of a pipeline?
AYes, but you lose index optimization. Rule of thumb: put it first whenever possible.
QWhy place $match at the start of the pipeline?
AFiltering early reduces the data volume passed to later stages and lets $match use an index, which significantly boosts performance. Placed later it still works but cannot use indexes.