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)

JavaScript

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

JavaScript

Example 1: Simplest — total number of movies

JavaScript

Output:

JSON

→ One document, one field, that’s it.

Example 2: Count after filtering (most common real usage)

JavaScript

Output:

JSON

→ Only Indian movies are counted.

Example 3: Count after complex filtering + unwind

JavaScript

Output:

JSON

→ Counts how many “Action” genre entries exist in movies from 2022 onwards.

Example 4: Compare count vs $group (very important difference)

JavaScript

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!

  1. Count how many movies are from India
  2. Count how many movies have rating ≥ 8.2
  3. Count how many “Action” genre entries exist (unwind → match → count)
  4. 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 😄

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *