Générer des rapports
Dans cette étape finale, vous allez apprendre à générer des rapports plus complexes à l'aide du cadre d'agrégation de MongoDB. Nous allons combiner plusieurs étapes d'agrégation pour créer des rapports instructifs à partir de notre collection de librairie.
Tout d'abord, vérifions notre collection existante :
use bookstore
db.books.find()
- Rapport d'inventaire de livres complet :
db.books.aggregate([
{
$project: {
titre: 1,
totalValue: { $multiply: ["$prix", "$quantité"] },
inventoryStatus: {
$switch: {
branches: [
{ case: { $lt: ["$quantité", 30] }, then: "Stock bas" },
{ case: { $gte: ["$quantité", 30] }, then: "En stock" }
]
}
}
}
},
{
$sort: { totalValue: -1 }
}
]);
Sortie exemple :
[
{
_id: ObjectId("..."),
titre: "Python Basics",
totalValue: 1499,50,
inventoryStatus: "En stock"
},
...
]
- Rapport de répartition des plages de prix :
db.books.aggregate([
{
$bucket: {
groupBy: "$prix",
boundaries: [0, 35, 45, 100],
default: "Autre",
output: {
count: { $sum: 1 },
titres: { $push: "$titre" }
}
}
}
]);
Sortie exemple :
[
{
_id: 0,
count: 2,
titres: ["Python Basics", "Web Development"]
},
{
_id: 35,
count: 1,
titres: ["MongoDB Essentials"]
},
...
]
- Rapport détaillé de performance commerciale :
db.books.aggregate([
{
$group: {
_id: {
priceCategory: {
$switch: {
branches: [
{ case: { $lt: ["$prix", 35] }, then: "Budget" },
{ case: { $gte: ["$prix", 35] }, then: "Premium" }
]
}
}
},
totalBooks: { $sum: 1 },
totalQuantity: { $sum: "$quantité" },
totalValue: { $sum: { $multiply: ["$prix", "$quantité"] } },
avgPrice: { $avg: "$prix" }
}
},
{
$project: {
_id: 0,
priceCategory: "$_id.priceCategory",
totalBooks: 1,
totalQuantity: 1,
totalValue: { $round: ["$totalValue", 2] },
avgPrice: { $round: ["$avgPrice", 2] }
}
}
]);
Sortie exemple :
[
{
priceCategory: "Budget",
totalBooks: 2,
totalQuantity: 90,
totalValue: 2984,50,
avgPrice: 32,37
},
{
priceCategory: "Premium",
totalBooks: 2,
totalQuantity: 55,
totalValue: 2212,75,
avgPrice: 42,75
}
]