Chapter 19: MongoDB Aggregation $count
1. What does $count actually do? (Very clear teacher explanation)
$count is a very simple stage that:
Counts how many documents reached this point in the pipeline and outputs ONE SINGLE DOCUMENT with only one field containing that count.
It’s the aggregation equivalent of .count() / .countDocuments() in normal queries — but inside the pipeline.
Most important points to remember:
- It replaces all previous documents with exactly one new document
- The output document has only one field (the name you choose)
- It is very fast because it doesn’t need to keep any document data — just a number
- It is almost always used near the end of the pipeline (after filtering, grouping, etc.)
2. Syntax (super short & sweet)
|
0 1 2 3 4 5 6 |
{ $count: "fieldNameYouChoose" } |
The string you put inside is the name of the output field.
Common names people use:
- “total”
- “count”
- “documentCount”
- “movieCount”
- “totalOrders”
- “resultCount”
3. Hands-on Examples — Using Our Movie Collection
|
0 1 2 3 4 5 6 |
use movieAnalytics2026 |
Example 1: Simplest — total number of movies
|
0 1 2 3 4 5 6 7 8 |
db.movies.aggregate([ { $count: "totalMovies" } ]) |
Output:
|
0 1 2 3 4 5 6 |
{ "totalMovies": 4 } |
→ One document, one field, that’s it.
Example 2: Count after filtering (most common real usage)
|
0 1 2 3 4 5 6 7 8 9 |
db.movies.aggregate([ { $match: { country: "India" } }, { $count: "indianMovies" } ]) |
Output:
|
0 1 2 3 4 5 6 |
{ "indianMovies": 3 } |
→ Only Indian movies are counted.
Example 3: Count after complex filtering + unwind
|
0 1 2 3 4 5 6 7 8 9 10 11 |
db.movies.aggregate([ { $match: { year: { $gte: 2022 } } }, { $unwind: "$genres" }, { $match: { genres: "Action" } }, { $count: "recentActionMovies" } ]) |
Output:
|
0 1 2 3 4 5 6 |
{ "recentActionMovies": 3 } |
→ Counts how many “Action” genre entries exist in movies from 2022 onwards.
Example 4: Compare count vs $group (very important difference)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
// Using $count (simple total) db.movies.aggregate([ { $match: { rating: { $gte: 8 } } }, { $count: "highRatedCount" } ]) // → { "highRatedCount": 4 } // Using $group (can do more) db.movies.aggregate([ { $group: { _id: null, highRatedCount: { $sum: 1 } } } ]) // → { "_id": null, "highRatedCount": 4 } |
When to choose $count over $group?
| Situation | Use $count? | Use $group? | Why? |
|---|---|---|---|
| You only need one total count | Yes | Possible | $count is shorter, clearer, slightly faster |
| You need multiple counts or other stats | No | Yes | $group allows $sum, $avg, $push, etc. at the same time |
| You want to count per group | No | Yes | $group with _id: “$category” + $sum: 1 |
| Final stage — just need “total: 42” | Yes | — | Very clean output |
4. Quick Cheat Sheet Table — Your $count Reference
| Goal | Typical Pipeline Ending | Output looks like | When to prefer $count over $group |
|---|---|---|---|
| Total documents after filter | … → $match → $count: “total” | { “total”: 142 } | Yes — simpler |
| Count after unwind + filter | … → $unwind → $match → $count: “items” | { “items”: 317 } | Yes |
| Final count in dashboard/report | … → $group → $sort → $limit → $count | { “shownItems”: 10 } | Yes — clean final number |
| Count per category (e.g. per genre) | … → $unwind → $group: { _id: “$genres”, count: … } | Multiple docs | No — use $group |
| Just want to know “how many match?” quickly | { $count: “matches” } | One doc with your field name | Yes — shortest way |
5. Mini Exercise — Try Right Now in mongosh!
- Count how many movies are from India
- Count how many movies have rating ≥ 8.2
- Count how many “Action” genre entries exist (unwind → match → count)
- Compare two pipelines:
- One with $count: “total”
- One with $group: { _id: null, total: { $sum: 1 } } → See they give same number but different output shape
Understood beta? $count is small and humble, but it makes your analytics pipelines cleaner, more readable, and slightly faster when you only need a number at the end.
Next class — what do you want?
- $facet — run multiple pipelines in parallel (very powerful for dashboards)
- $unwind deep dive (because it often appears before $group & $count)
- Common patterns: count + top N + average in one pipeline
- Or finally build a complete “Valentine Movie Stats Report” using all stages we’ve learned?
Tell me — class is still going strong! 🚀❤️
Any confusion with $count? Ask freely — we’ll do more live examples together 😄
