MongoDB Aggregation $match

MongoDB Tutorial

MongoDB Aggregation $match 🎯

In MongoDB, the $match stage is used in an Aggregation Pipeline to filter documents based on conditions—just like WHERE in SQL or find() in MongoDB.

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

db.collection.aggregate([
{ $match: { condition } }
])

1️⃣ Simple $match Example

Find students from BA course

db.students.aggregate([
{ $match: { course: "BA" } }
])

2️⃣ $match with Comparison Operators

Age greater than 20

db.students.aggregate([
{ $match: { age: { $gt: 20 } } }
])

3️⃣ $match with Multiple Conditions (AND)

db.students.aggregate([
{
$match: {
course: "BA",
age: { $gte: 18 }
}
}
])

📌 Conditions in the same object work as AND


4️⃣ $match with Logical Operators

$or

db.students.aggregate([
{
$match: {
$or: [
{ course: "BA" },
{ course: "BSc" }
]
}
}
])

$and

db.students.aggregate([
{
$match: {
$and: [
{ age: { $gt: 20 } },
{ course: "BA" }
]
}
}
])

5️⃣ $match with Regular Expression

Name starts with “A”

db.students.aggregate([
{
$match: {
name: { $regex: "^A", $options: "i" }
}
}
])

6️⃣ $match with Arrays

Match array value

db.students.aggregate([
{ $match: { skills: "MongoDB" } }
])

Using $all

db.students.aggregate([
{
$match: {
skills: { $all: ["HTML", "CSS"] }
}
}
])

7️⃣ $match Before $group (Best Practice 👍)

Count BA students above age 20

db.students.aggregate([
{ $match: { course: "BA", age: { $gt: 20 } } },
{
$group: {
_id: "$course",
total: { $sum: 1 }
}
}
])

⚡ Filtering first = faster aggregation


$match vs find()

$match find()
Aggregation stage Query method
Works with $group, $project No aggregation
Supports pipelines Simple retrieval

Example:

db.students.find({ age: { $gt: 20 } })

SQL vs MongoDB $match

SQL

SELECT * FROM students WHERE age > 20;

MongoDB

db.students.aggregate([
{ $match: { age: { $gt: 20 } } }
])

Common Mistakes ❌

  • Placing $match too late in pipeline

  • Forgetting $ in operators (gt ❌ → $gt ✅)

  • Expecting $match to transform data (it only filters)


Performance Tips ⚡

  • Place $match as early as possible

  • Create indexes on frequently matched fields

  • Combine $match before $group and $sort


Quick Recap 🧠

$match // filter documents
$gt // greater than
$or // logical OR
$regex // pattern match

You may also like...