Generate Reports
In this final step, you'll learn how to generate more complex reports using MongoDB's aggregation framework. We'll combine multiple aggregation stages to create insightful reports from our bookstore collection.
First, let's verify our existing collection:
use bookstore
db.books.find()
- Comprehensive Book Inventory Report:
db.books.aggregate([
{
$project: {
title: 1,
totalValue: { $multiply: ["$price", "$quantity"] },
inventoryStatus: {
$switch: {
branches: [
{ case: { $lt: ["$quantity", 30] }, then: "Low Stock" },
{ case: { $gte: ["$quantity", 30] }, then: "In Stock" }
]
}
}
}
},
{
$sort: { totalValue: -1 }
}
]);
Example output:
[
{
_id: ObjectId("..."),
title: "Python Basics",
totalValue: 1499.50,
inventoryStatus: "In Stock"
},
...
]
- Price Range Distribution Report:
db.books.aggregate([
{
$bucket: {
groupBy: "$price",
boundaries: [0, 35, 45, 100],
default: "Other",
output: {
count: { $sum: 1 },
titles: { $push: "$title" }
}
}
}
]);
Example output:
[
{
_id: 0,
count: 2,
titles: ["Python Basics", "Web Development"]
},
{
_id: 35,
count: 1,
titles: ["MongoDB Essentials"]
},
...
]
- Detailed Sales Performance Report:
db.books.aggregate([
{
$group: {
_id: {
priceCategory: {
$switch: {
branches: [
{ case: { $lt: ["$price", 35] }, then: "Budget" },
{ case: { $gte: ["$price", 35] }, then: "Premium" }
]
}
}
},
totalBooks: { $sum: 1 },
totalQuantity: { $sum: "$quantity" },
totalValue: { $sum: { $multiply: ["$price", "$quantity"] } },
avgPrice: { $avg: "$price" }
}
},
{
$project: {
_id: 0,
priceCategory: "$_id.priceCategory",
totalBooks: 1,
totalQuantity: 1,
totalValue: { $round: ["$totalValue", 2] },
avgPrice: { $round: ["$avgPrice", 2] }
}
}
]);
Example output:
[
{
priceCategory: "Budget",
totalBooks: 2,
totalQuantity: 90,
totalValue: 2984.50,
avgPrice: 32.37
},
{
priceCategory: "Premium",
totalBooks: 2,
totalQuantity: 55,
totalValue: 2212.75,
avgPrice: 42.75
}
]