本文由大模型生成
MongoDB 的 aggregate
方法用于对数据进行聚合操作,可以执行复杂的数据分析、转换和汇总。聚合管道(Aggregation Pipeline)是一系列处理文档并返回计算结果的阶段(stages)。每个阶段都接收输入文档流,然后输出修改后的文档流给下一个阶段,直到管道结束。
聚合管道的主要阶段
- $match:过滤文档,只传递符合条件的文档到下一个阶段。
- $project:重新构造文档,比如添加、删除或重命名字段。
- $group:根据指定的条件对文档进行分组,并可以对每个组进行一些聚合操作(如计算总数、平均值等)。
- $sort:对文档进行排序。
- $limit:限制传递给下一个阶段的文档数量。
- $skip:跳过指定数量的文档。
- $unwind:将数组类型的字段拆分成多个文档。
- $lookup:执行左外连接到另一个集合。
- $out:将聚合结果写入到一个新的集合中。
- $count:计算输入文档的数量。
示例
假设有一个 orders
集合,包含以下文档:
[
{ "_id": 1, "item": "apple", "quantity": 5, "price": 3, "date": "2023-10-01" },
{ "_id": 2, "item": "banana", "quantity": 2, "price": 4, "date": "2023-10-01" },
{ "_id": 3, "item": "apple", "quantity": 7, "price": 3, "date": "2023-10-02" },
{ "_id": 4, "item": "orange", "quantity": 8, "price": 2, "date": "2023-10-02" }
]
示例 1:计算每种水果的总数量和总价格
db.orders.aggregate([
{
$group: {
_id: "$item",
totalQuantity: { $sum: "$quantity" },
totalPrice: { $sum: { $multiply: ["$quantity", "$price"] } }
}
}
])
输出:
[
{ "_id": "banana", "totalQuantity": 2, "totalPrice": 8 },
{ "_id": "apple", "totalQuantity": 12, "totalPrice": 30 },
{ "_id": "orange", "totalQuantity": 8, "totalPrice": 16 }
]
示例 2:过滤并排序文档
假设我们想获取总数量大于 5 的水果,并按总价格降序排列:
db.orders.aggregate([
{
$group: {
_id: "$item",
totalQuantity: { $sum: "$quantity" },
totalPrice: { $sum: { $multiply: ["$quantity", "$price"] } }
}
},
{
$match: { totalQuantity: { $gt: 5 } }
},
{
$sort: { totalPrice: -1 }
}
])
输出:
[
{ "_id": "apple", "totalQuantity": 12, "totalPrice": 30 },
{ "_id": "orange", "totalQuantity": 8, "totalPrice": 16 }
]
示例 3:将结果写入新集合
将上述结果写入一个新的集合 order_totals
:
db.orders.aggregate([
{
$group: {
_id: "$item",
totalQuantity: { $sum: "$quantity" },
totalPrice: { $sum: { $multiply: ["$quantity", "$price"] } }
}
},
{
$match: { totalQuantity: { $gt: 5 } }
},
{
$sort: { totalPrice: -1 }
},
{
$out: "order_totals"
}
])
现在,你可以在 order_totals
集合中看到聚合结果。
总结
MongoDB 的 aggregate
方法非常强大,支持多种数据聚合操作。通过组合不同的阶段,你可以实现复杂的数据分析和转换任务。在实际应用中,根据需求选择合适的阶段和操作符,可以高效地处理和分析数据。