0
0
MongoDBquery~30 mins

$group stage for aggregation in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
$group Stage for Aggregation in MongoDB
📖 Scenario: You work at a bookstore that keeps sales records in a MongoDB collection. Each sale document records the bookTitle, author, and copiesSold. You want to find out how many copies of each book were sold in total.
🎯 Goal: Build a MongoDB aggregation pipeline using the $group stage to calculate the total copies sold for each book.
📋 What You'll Learn
Create a collection named sales with documents containing bookTitle, author, and copiesSold fields.
Define a variable pipeline that holds the aggregation stages.
Use the $group stage to group documents by bookTitle and calculate the total copiesSold for each book.
Add a final stage to sort the results by total copies sold in descending order.
💡 Why This Matters
🌍 Real World
Bookstores and many businesses use MongoDB aggregation pipelines to analyze sales data and generate reports.
💼 Career
Understanding the <code>$group</code> stage is essential for data analysts and backend developers working with MongoDB to summarize and aggregate data efficiently.
Progress0 / 4 steps
1
Create the sales data collection
Create a variable called sales that is a list of documents with these exact entries: { bookTitle: "The Hobbit", author: "J.R.R. Tolkien", copiesSold: 5 }, { bookTitle: "1984", author: "George Orwell", copiesSold: 8 }, { bookTitle: "The Hobbit", author: "J.R.R. Tolkien", copiesSold: 3 }, { bookTitle: "Dune", author: "Frank Herbert", copiesSold: 7 }.
MongoDB
Need a hint?

Use a list of dictionaries with the exact keys and values as shown.

2
Define the aggregation pipeline variable
Create a variable called pipeline and set it to an empty list to hold the aggregation stages.
MongoDB
Need a hint?

Just create an empty list named pipeline.

3
Add the $group stage to sum copies sold by bookTitle
Add a $group stage to the pipeline list. Group by _id set to $bookTitle and create a field totalCopies that sums copiesSold.
MongoDB
Need a hint?

Use { "$group": { "_id": "$bookTitle", "totalCopies": { "$sum": "$copiesSold" } } } inside the pipeline list.

4
Add a $sort stage to order results by totalCopies descending
Add a $sort stage to the pipeline list that sorts by totalCopies in descending order (-1).
MongoDB
Need a hint?

Add { "$sort": { "totalCopies": -1 } } as the last stage in the pipeline list.