MongoDB Aggregation $count

MongoDB Tutorial

MongoDB Aggregation $count

In MongoDB Aggregation $count is an aggregation stage used to count the number of documents passing through the pipeline.

 Think of $count as:

SQL → COUNT(*)


 What is MongoDB Aggregation $count?

  • Counts documents in an aggregation pipeline

  • Returns the result as a new field

  • Ends the pipeline (no data after it)


1️⃣ Basic Syntax

 The value is the output field name.


2️⃣ Simple Example (Count All Documents)

Scenario

Count all documents in the users collection.

Output

{ "totalUsers": 5 }

3️⃣ $count with $match (Most Common Use)

Scenario

Count users from Delhi.

$match filters documents
$count counts filtered result


4️⃣ $count with $group (Interview Tip)

Count number of documents per group.

$count counts total documents
$group counts per category


5️⃣ $count vs countDocuments() (Very Important)

MethodUsage
$countInside aggregation
countDocuments()Simple collection count
estimatedDocumentCount()Fast but approximate

Example:


6️⃣ $count Rules & Limitations

✔ Must be a pipeline stage
✔ Usually placed at the end
✔ Returns one document only
✔ Field name cannot start with $


 Key Points (Very Important for Exams & Interviews)

$count counts documents in aggregation
✔ Similar to SQL COUNT(*)
✔ Used after $match, $lookup, etc.
✔ Outputs a single document
✔ Field name is user-defined


 Common Interview Questions

Q1. What does $count do in MongoDB?
👉 Counts documents in aggregation pipeline

Q2. Where is $count used?
👉 Inside aggregation only

Q3. Can $count group data?
👉 ❌ No, use $group

Q4. $count vs countDocuments()?
👉 $count → aggregation
👉 countDocuments() → normal query


 Summary

 That’s everything you need to know about MongoDB Aggregation $count.

You may also like...