MongoDB Aggregation $count
MongoDB Aggregation $count 🔢
What does $count do?
-
Counts documents after filtering or transformation
-
Returns a single document with the count
-
Similar to
COUNT(*)in SQL -
Often used after
$match
Basic Syntax
📌 "fieldName" is the name of the output field that will store the count.
1️⃣ Simple $count Example
Count all students
Output
2️⃣ $count with $match (Most Common)
Count BA students
3️⃣ $count with Conditions
Count students older than 20
4️⃣ $count After $group
Count number of distinct courses
📌 $group first creates unique groups, $count then counts them.
5️⃣ $count vs $group + $sum
Using $count (Simpler)
Using $group
$count |
$group + $sum |
|---|---|
| Simple & clean | More flexible |
| Single output field | Multiple aggregations |
| Best for pure counts | Best for reports |
$count vs countDocuments()
$count |
countDocuments() |
|---|---|
| Aggregation stage | Query method |
| Used in pipeline | Used with find |
Works after $group |
Cannot group |
Example:
SQL vs MongoDB $count
SQL
MongoDB
Best Practices 👍
-
Always place
$matchbefore$count -
Use
$countfor simple totals -
Use
$groupwhen you need multiple metrics
Common Mistakes ❌
-
Expecting
$countto return multiple documents -
Forgetting output field name
-
Using
$countwithout understanding pipeline order
