Counting Documents with $count Accumulator in MongoDB
📖 Scenario: You are managing a small online bookstore database. You want to find out how many books are available in your collection.
🎯 Goal: Build a MongoDB aggregation pipeline that counts the total number of books in the books collection using the $count accumulator.
📋 What You'll Learn
Create a books collection with exactly 5 book documents, each having title and author fields.
Add a variable collectionName that stores the string "books".
Write an aggregation pipeline that uses $count to count all documents in the books collection.
Assign the aggregation pipeline result to a variable called countResult.
💡 Why This Matters
🌍 Real World
Counting documents is a common task in databases to get quick summaries, like how many books, users, or orders exist.
💼 Career
Database developers and analysts often use aggregation pipelines with <code>$count</code> to generate reports and insights.
Progress0 / 4 steps
1
Create the books collection with 5 book documents
Create a variable called books that is an array containing exactly these 5 documents: { title: "The Hobbit", author: "J.R.R. Tolkien" }, { title: "1984", author: "George Orwell" }, { title: "To Kill a Mockingbird", author: "Harper Lee" }, { title: "Pride and Prejudice", author: "Jane Austen" }, and { title: "The Great Gatsby", author: "F. Scott Fitzgerald" }.
MongoDB
Hint
Use an array of objects with the exact titles and authors given.
2
Add a variable for the collection name
Create a variable called collectionName and set it to the string "books".
MongoDB
Hint
Just assign the string "books" to collectionName.
3
Write an aggregation pipeline using $count
Create a variable called pipeline that is an array containing one stage: an object with the key $count and the value "totalBooks".
MongoDB
Hint
The pipeline is an array with one object: { $count: "totalBooks" }.
4
Assign the aggregation result to countResult
Create a variable called countResult and assign it the result of calling db.collection(collectionName).aggregate(pipeline).toArray().
MongoDB
Hint
Use db.collection(collectionName).aggregate(pipeline).toArray() to get the count result.
Practice
(1/5)
1. What does the $count accumulator do in a MongoDB aggregation pipeline?
easy
A. Counts the number of documents in each group
B. Sums the values of a field in each group
C. Finds the maximum value in each group
D. Calculates the average of a field in each group
Solution
Step 1: Understand the purpose of $count
The $count accumulator is used inside the $group stage to count how many documents belong to each group.
Step 2: Compare with other accumulators
Unlike $sum, $max, or $avg, $count does not operate on field values but counts documents.
Final Answer:
Counts the number of documents in each group -> Option A
Quick Check:
$count = document count [OK]
Hint: Remember: $count counts documents, no field needed [OK]
Common Mistakes:
Thinking $count sums field values
Using $count outside $group stage
Expecting $count to take arguments
2. Which of the following is the correct syntax to count documents per category using $count in a $group stage?
The $count accumulator does not accept any arguments; passing "$amount" is invalid syntax.
Step 2: Verify other parts
The _id field and pipeline structure are correct; no $match is required before $group, and $count is inside aggregation.
Final Answer:
Using $count with a field argument is invalid -> Option C
Quick Check:
$count must have empty braces {} [OK]
Hint: Never pass a field to $count, use empty braces {} [OK]
Common Mistakes:
Passing a field name to $count
Thinking $count needs $match before $group
Confusing $count with $sum
5. You want to find how many orders each customer placed, but only for customers with more than 2 orders. Which aggregation pipeline correctly uses $count to achieve this?