How to Use $match in Aggregation in MongoDB
Use the
$match stage in a MongoDB aggregation pipeline to filter documents by specifying query conditions similar to a find query. It selects only the documents that match the criteria and passes them to the next pipeline stage.Syntax
The $match stage takes a query object that defines the filtering criteria. It works like a standard MongoDB query inside the aggregation pipeline.
{ $match: {- Filters documents where: } } <field>meets<condition>.- The condition can use operators like
$eq,$gt,$in, etc. - Only documents matching the condition continue to the next stage.
json
{
$match: { <field>: <condition> }
}Example
This example shows how to use $match to filter documents where the status field equals "active" in a collection named users.
mongodb
db.users.aggregate([
{ $match: { status: "active" } }
])Output
[
{ "_id": 1, "name": "Alice", "status": "active" },
{ "_id": 3, "name": "Charlie", "status": "active" }
]
Common Pitfalls
Common mistakes when using $match include:
- Using
$matchoutside an aggregation pipeline (it only works insideaggregate()). - Writing query conditions incorrectly, such as missing quotes around string values.
- Placing
$matchafter expensive stages instead of early to improve performance.
mongodb
/* Wrong: Using $match as a separate query */ db.users.$match({ status: "active" }) /* Correct: Using $match inside aggregate pipeline */ db.users.aggregate([ { $match: { status: "active" } } ])
Quick Reference
| Operator | Description | Example |
|---|---|---|
| $eq | Matches values equal to specified value | { $match: { age: { $eq: 30 } } } |
| $gt | Matches values greater than specified value | { $match: { score: { $gt: 80 } } } |
| $in | Matches any value in an array | { $match: { category: { $in: ["A", "B"] } } } |
| $ne | Matches values not equal to specified value | { $match: { status: { $ne: "inactive" } } } |
Key Takeaways
Use $match inside an aggregation pipeline to filter documents by conditions.
$match syntax is similar to a standard MongoDB query object.
Place $match early in the pipeline for better performance.
Ensure query conditions are correctly formatted with proper operators.
$match only passes matching documents to the next pipeline stage.