介绍
在本实验中,你将学习如何在 MongoDB 中执行基本的聚合操作,包括计算总和、查找最小值和最大值、统计文档数量、计算平均值以及生成报告。实验通过使用一个示例书籍集合来演示 MongoDB 聚合框架的强大功能,帮助你从数据中提取有意义的见解。
实验将逐步引导你完成操作,首先从计算总值开始,例如书籍的总价值和总数量。接着,你将学习如何查找书籍的最低和最高价格、统计文档数量以及计算书籍的平均价格。最后,你将探索如何生成报告以汇总集合中的数据。
在本实验中,你将学习如何在 MongoDB 中执行基本的聚合操作,包括计算总和、查找最小值和最大值、统计文档数量、计算平均值以及生成报告。实验通过使用一个示例书籍集合来演示 MongoDB 聚合框架的强大功能,帮助你从数据中提取有意义的见解。
实验将逐步引导你完成操作,首先从计算总值开始,例如书籍的总价值和总数量。接着,你将学习如何查找书籍的最低和最高价格、统计文档数量以及计算书籍的平均价格。最后,你将探索如何生成报告以汇总集合中的数据。
在这一步骤中,你将学习如何使用 MongoDB 的聚合框架计算总值。我们将使用一个示例书籍集合来演示如何对数值字段进行求和。
首先,启动 MongoDB shell 并创建一个示例书籍集合:
mongosh
接下来,创建一个包含价格的书籍集合:
use bookstore
db.books.insertMany([
{ title: "Python Basics", price: 29.99, quantity: 50 },
{ title: "MongoDB Essentials", price: 39.99, quantity: 30 },
{ title: "Data Science Guide", price: 45.50, quantity: 25 },
{ title: "Web Development", price: 34.75, quantity: 40 }
])
要计算所有书籍的总价值,我们可以使用 $sum
聚合操作符:
db.books.aggregate([
{
$group: {
_id: null,
totalBookValue: { $sum: { $multiply: ["$price", "$quantity"] } }
}
}
]);
示例输出:
[
{
_id: null,
totalBookValue: 5197.25
}
]
让我们分解一下这个聚合操作的作用:
$group
将所有文档分组_id: null
表示我们对整个集合进行聚合$multiply
计算每本书的总价值(价格 * 数量)$sum
将这些值相加你还可以计算其他总和,例如书籍的总数量:
db.books.aggregate([
{
$group: {
_id: null,
totalQuantity: { $sum: "$quantity" }
}
}
]);
示例输出:
[
{
_id: null,
totalQuantity: 145
}
]
在这一步骤中,你将学习如何使用 MongoDB 的聚合框架查找最小值和最大值。我们将继续使用上一步中的书店集合。
首先,验证我们现有的集合:
use bookstore
db.books.find()
要查找书籍的最低和最高价格,我们可以使用 $min
和 $max
聚合操作符:
db.books.aggregate([
{
$group: {
_id: null,
lowestPrice: { $min: "$price" },
highestPrice: { $max: "$price" }
}
}
]);
示例输出:
[
{
_id: null,
lowestPrice: 29.99,
highestPrice: 45.50
}
]
我们还可以查找最小和最大数量:
db.books.aggregate([
{
$group: {
_id: null,
lowestQuantity: { $min: "$quantity" },
highestQuantity: { $max: "$quantity" }
}
}
]);
示例输出:
[
{
_id: null,
lowestQuantity: 25,
highestQuantity: 50
}
]
为了获得更详细的见解,我们可以查找价格最低和最高的书籍:
db.books.aggregate([
{
$sort: { price: 1 }
},
{
$limit: 1
},
{
$project: {
title: 1,
price: 1
}
}
]);
示例输出:
[
{
_id: ObjectId("..."),
title: "Python Basics",
price: 29.99
}
]
在这一步骤中,你将学习使用多种技术在 MongoDB 中统计文档数量的不同方法。我们将继续使用之前步骤中的书店集合。
首先,验证我们现有的集合:
use bookstore
db.books.find()
在 MongoDB 中,有多种方法可以统计文档数量。让我们逐一探索:
db.books.countDocuments();
示例输出:
4
db.books.countDocuments({ price: { $gt: 35 } });
这将统计价格大于 35 的书籍数量。
示例输出:
2
db.books.aggregate([
{
$match: { quantity: { $gte: 30 } }
},
{
$count: "booksWithHighQuantity"
}
]);
这将统计数量大于或等于 30 的书籍数量。
示例输出:
[
{
booksWithHighQuantity: 3
}
]
db.books.aggregate([
{
$group: {
_id: "$title",
count: { $sum: 1 }
}
}
]);
这将显示每本书的标题出现的次数。
示例输出:
[
{
_id: "Python Basics",
count: 1
},
...
]
在这一步骤中,你将学习如何使用 MongoDB 的聚合框架计算平均值。我们将继续使用之前步骤中的书店集合。
首先,验证我们现有的集合:
use bookstore
db.books.find()
db.books.aggregate([
{
$group: {
_id: null,
averagePrice: { $avg: "$price" }
}
}
]);
示例输出:
[
{
_id: null,
averagePrice: 37.56
}
]
db.books.aggregate([
{
$group: {
_id: null,
averageQuantity: { $avg: "$quantity" }
}
},
{
$project: {
averageQuantity: { $round: ["$averageQuantity", 2] }
}
}
]);
示例输出:
[
{
_id: null,
averageQuantity: 36.25
}
]
db.books.aggregate([
{
$group: {
_id: {
priceCategory: {
$switch: {
branches: [
{ case: { $lt: ["$price", 35] }, then: "Budget" },
{ case: { $gte: ["$price", 35] }, then: "Premium" }
]
}
}
},
averagePrice: { $avg: "$price" }
}
}
]);
示例输出:
[
{
_id: { priceCategory: "Budget" },
averagePrice: 32.37
},
{
_id: { priceCategory: "Premium" },
averagePrice: 42.75
}
]
在这最后一步中,你将学习如何使用 MongoDB 的聚合框架生成更复杂的报告。我们将结合多个聚合阶段,从书店集合中创建有洞察力的报告。
首先,验证我们现有的集合:
use bookstore
db.books.find()
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 }
}
]);
示例输出:
[
{
_id: ObjectId("..."),
title: "Python Basics",
totalValue: 1499.50,
inventoryStatus: "In Stock"
},
...
]
db.books.aggregate([
{
$bucket: {
groupBy: "$price",
boundaries: [0, 35, 45, 100],
default: "Other",
output: {
count: { $sum: 1 },
titles: { $push: "$title" }
}
}
}
]);
示例输出:
[
{
_id: 0,
count: 2,
titles: ["Python Basics", "Web Development"]
},
{
_id: 35,
count: 1,
titles: ["MongoDB Essentials"]
},
...
]
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] }
}
}
]);
示例输出:
[
{
priceCategory: "Budget",
totalBooks: 2,
totalQuantity: 90,
totalValue: 2984.50,
avgPrice: 32.37
},
{
priceCategory: "Premium",
totalBooks: 2,
totalQuantity: 55,
totalValue: 2212.75,
avgPrice: 42.75
}
]
在本实验中,你将学习如何使用 MongoDB 的聚合框架计算总和、查找最小值和最大值、统计文档数量、计算平均值以及生成报告。首先,你将使用 $sum
聚合操作符计算示例书籍集合中所有书籍的总价值。你还将学习如何计算书籍的总数量。接下来,你将使用 $min
和 $max
聚合操作符查找书籍的最低和最高价格。然后,你将学习如何统计集合中的文档数量并计算书籍的平均价格。