0
0
MongodbHow-ToBeginner · 3 min read

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 $match outside an aggregation pipeline (it only works inside aggregate()).
  • Writing query conditions incorrectly, such as missing quotes around string values.
  • Placing $match after 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

OperatorDescriptionExample
$eqMatches values equal to specified value{ $match: { age: { $eq: 30 } } }
$gtMatches values greater than specified value{ $match: { score: { $gt: 80 } } }
$inMatches any value in an array{ $match: { category: { $in: ["A", "B"] } } }
$neMatches 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.