MongoDB Aggregation $count

MongoDB Tutorial

MongoDB Aggregation $count 🔢

In MongoDB, the $count stage in the Aggregation Pipeline is used to count the number of documents that pass through the pipeline and return the result as a single document.

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

db.collection.aggregate([
{ $count: "fieldName" }
])

📌 "fieldName" is the name of the output field that will store the count.


1️⃣ Simple $count Example

Count all students

db.students.aggregate([
{ $count: "totalStudents" }
])

Output

{ totalStudents: 25 }

2️⃣ $count with $match (Most Common)

Count BA students

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

3️⃣ $count with Conditions

Count students older than 20

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

4️⃣ $count After $group

Count number of distinct courses

db.students.aggregate([
{
$group: {
_id: "$course"
}
},
{ $count: "totalCourses" }
])

📌 $group first creates unique groups, $count then counts them.


5️⃣ $count vs $group + $sum

Using $count (Simpler)

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

Using $group

db.students.aggregate([
{
$group: {
_id: null,
total: { $sum: 1 }
}
}
])
$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:

db.students.countDocuments({ course: "BA" })

SQL vs MongoDB $count

SQL

SELECT COUNT(*) FROM students WHERE course = 'BA';

MongoDB

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

Best Practices 👍

  • Always place $match before $count

  • Use $count for simple totals

  • Use $group when you need multiple metrics


Common Mistakes ❌

  • Expecting $count to return multiple documents

  • Forgetting output field name

  • Using $count without understanding pipeline order


Quick Recap 🧠

$count // count documents
$match // filter first
$group // count groups

You may also like...