0
0
MongoDBquery~30 mins

$count accumulator in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a hint?

Use db.collection(collectionName).aggregate(pipeline).toArray() to get the count result.