MongoDB Aggregation $match
MongoDB Aggregation $match 🎯
What does $match do?
-
Filters documents using query operators
-
Reduces data early → better performance
-
Can use indexes
-
Usually placed at the start of the pipeline
Basic Syntax
1️⃣ Simple $match Example
Find students from BA course
2️⃣ $match with Comparison Operators
Age greater than 20
3️⃣ $match with Multiple Conditions (AND)
📌 Conditions in the same object work as AND
4️⃣ $match with Logical Operators
$or
$and
5️⃣ $match with Regular Expression
Name starts with “A”
6️⃣ $match with Arrays
Match array value
Using $all
7️⃣ $match Before $group (Best Practice 👍)
Count BA students above age 20
⚡ Filtering first = faster aggregation
$match vs find()
$match |
find() |
|---|---|
| Aggregation stage | Query method |
Works with $group, $project |
No aggregation |
| Supports pipelines | Simple retrieval |
Example:
SQL vs MongoDB $match
SQL
MongoDB
Common Mistakes ❌
-
Placing
$matchtoo late in pipeline -
Forgetting
$in operators (gt❌ →$gt✅) -
Expecting
$matchto transform data (it only filters)
Performance Tips ⚡
-
Place
$matchas early as possible -
Create indexes on frequently matched fields
-
Combine
$matchbefore$groupand$sort
