0
0
MongoDBquery~30 mins

Aggregation for reporting dashboards in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Aggregation for reporting dashboards
📖 Scenario: You work for an online store that wants to create a simple sales report dashboard. The dashboard will show total sales and the number of orders per product category.
🎯 Goal: Build a MongoDB aggregation pipeline step-by-step to calculate total sales and order counts grouped by product category.
📋 What You'll Learn
Create a sales collection with sample sales documents
Add a filter stage to select sales from the last month
Group sales by category to calculate total sales amount and order count
Sort the results by total sales in descending order
💡 Why This Matters
🌍 Real World
Aggregation pipelines are used in real dashboards to summarize and analyze sales data quickly.
💼 Career
Understanding aggregation is essential for data analysts and backend developers working with MongoDB to build reports.
Progress0 / 4 steps
1
DATA SETUP: Create the sales collection with sample documents
Create a variable called sales that contains an array of 5 sales documents. Each document must have these exact fields and values: { product: 'Laptop', category: 'Electronics', amount: 1200, date: new Date('2024-05-10') }, { product: 'Headphones', category: 'Electronics', amount: 150, date: new Date('2024-05-15') }, { product: 'Coffee Maker', category: 'Home Appliances', amount: 80, date: new Date('2024-05-20') }, { product: 'Blender', category: 'Home Appliances', amount: 60, date: new Date('2024-04-25') }, { product: 'Notebook', category: 'Stationery', amount: 5, date: new Date('2024-05-18') }.
MongoDB
Need a hint?

Use const sales = [ ... ] and include the exact documents with the given fields and values.

2
CONFIGURATION: Define the date filter for last month sales
Create a variable called lastMonth and set it to a JavaScript Date object representing May 1, 2024.
MongoDB
Need a hint?

Use const lastMonth = new Date('2024-05-01') to set the date filter.

3
CORE LOGIC: Build the aggregation pipeline to filter and group sales
Create a variable called pipeline that is an array with these stages: 1) a $match stage to filter sales with date greater than or equal to lastMonth, 2) a $group stage that groups by category and calculates totalSales as the sum of amount and orderCount as the count of documents.
MongoDB
Need a hint?

Use { $match: { date: { $gte: lastMonth } } } and { $group: { _id: "$category", totalSales: { $sum: "$amount" }, orderCount: { $sum: 1 } } } in the pipeline array.

4
COMPLETION: Add a $sort stage to order results by total sales
Add a $sort stage to the pipeline array that sorts documents by totalSales in descending order.
MongoDB
Need a hint?

Add { $sort: { totalSales: -1 } } as the last stage in the pipeline array.