0
0
MongoDBquery~30 mins

countDocuments method in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Counting Documents in a MongoDB Collection
📖 Scenario: You are managing a small library database. You want to find out how many books are in the collection and how many books belong to a specific genre.
🎯 Goal: Build a MongoDB query using the countDocuments method to count all books and then count books of a specific genre.
📋 What You'll Learn
Create a collection named books with sample book documents
Add a filter variable for the genre to count
Use countDocuments to count all books
Use countDocuments with the genre filter to count books of that genre
💡 Why This Matters
🌍 Real World
Counting documents is useful to know how many records match certain criteria in databases like MongoDB, such as counting users, orders, or products.
💼 Career
Database developers and data analysts often need to count records efficiently to generate reports and insights.
Progress0 / 4 steps
1
Create the books collection with sample documents
Create a variable called books that is an array containing these exact documents: { title: "The Hobbit", genre: "Fantasy" }, { title: "1984", genre: "Dystopian" }, { title: "The Catcher in the Rye", genre: "Fiction" }, { title: "The Lord of the Rings", genre: "Fantasy" }.
MongoDB
Need a hint?

Use an array of objects with the exact titles and genres given.

2
Add a filter variable for the genre
Create a variable called genreFilter and set it to an object that filters for books with genre equal to "Fantasy".
MongoDB
Need a hint?

Create an object with the key genre and value "Fantasy".

3
Count all books using countDocuments
Write a line that uses db.collection('books').countDocuments() to count all documents and assign the result to a variable called totalBooks.
MongoDB
Need a hint?

Use db.collection('books').countDocuments() and assign it to totalBooks.

4
Count books of the genre using countDocuments with filter
Write a line that uses db.collection('books').countDocuments(genreFilter) to count documents matching the genre filter and assign the result to a variable called fantasyBooks.
MongoDB
Need a hint?

Use countDocuments with genreFilter and assign to fantasyBooks.