0
0
MongoDBquery~5 mins

Aggregation for reporting dashboards in MongoDB

Choose your learning style9 modes available
Introduction
Aggregation helps combine and summarize data so you can see important information quickly on dashboards.
You want to count how many sales happened each day.
You need to find the average rating of products for a review dashboard.
You want to group users by country to see where most users come from.
You want to sum total revenue by month for a financial report.
You want to filter and sort data to show top-selling items on a dashboard.
Syntax
MongoDB
db.collection.aggregate([
  { stage1 },
  { stage2 },
  ...
])
Each stage processes data step-by-step, like a factory line.
Common stages include $match (filter), $group (summarize), $sort (order), and $project (select fields).
Examples
This finds total sales amount for each product where sales are completed.
MongoDB
db.sales.aggregate([
  { $match: { status: "completed" } },
  { $group: { _id: "$product", totalSales: { $sum: "$amount" } } }
])
This counts users per country and sorts countries by user count descending.
MongoDB
db.users.aggregate([
  { $group: { _id: "$country", count: { $sum: 1 } } },
  { $sort: { count: -1 } }
])
Sample Program
This query finds total money spent by each customer on shipped orders and sorts customers by highest spending first.
MongoDB
db.orders.aggregate([
  { $match: { status: "shipped" } },
  { $group: { _id: "$customerId", totalSpent: { $sum: "$price" } } },
  { $sort: { totalSpent: -1 } }
])
OutputSuccess
Important Notes
Aggregation pipelines can have many stages to shape data exactly as needed.
Always test your pipeline with sample data to check results before using in dashboards.
Use indexes on fields used in $match to speed up aggregation performance.
Summary
Aggregation combines data step-by-step to create summaries for dashboards.
Use stages like $match, $group, and $sort to filter, summarize, and order data.
Aggregation helps turn raw data into clear, useful reports.