Generiere Berichte
In diesem letzten Schritt lernen Sie, wie Sie mit dem Aggregationsframework von MongoDB komplexere Berichte generieren. Wir kombinieren mehrere Aggregationsstufen, um aus unserer Buchhandlungssammlung aufschlussreiche Berichte zu erstellen.
Lassen Sie uns zunächst unsere vorhandene Sammlung überprüfen:
use bookstore
db.books.find()
- Umfassender Buchbestandsbericht:
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 }
}
]);
Beispielausgabe:
[
{
_id: ObjectId("..."),
title: "Python Basics",
totalValue: 1499.50,
inventoryStatus: "In Stock"
},
...
]
- Preisbereichsverteilungsbericht:
db.books.aggregate([
{
$bucket: {
groupBy: "$price",
boundaries: [0, 35, 45, 100],
default: "Other",
output: {
count: { $sum: 1 },
titles: { $push: "$title" }
}
}
}
]);
Beispielausgabe:
[
{
_id: 0,
count: 2,
titles: ["Python Basics", "Web Development"]
},
{
_id: 35,
count: 1,
titles: ["MongoDB Essentials"]
},
...
]
- Detailierter Verkaufsleistungsbericht:
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] }
}
}
]);
Beispielausgabe:
[
{
priceCategory: "Budget",
totalBooks: 2,
totalQuantity: 90,
totalValue: 2984.50,
avgPrice: 32.37
},
{
priceCategory: "Premium",
totalBooks: 2,
totalQuantity: 55,
totalValue: 2212.75,
avgPrice: 42.75
}
]