推荐答案
db.collection.aggregate([
{ $match: { status: "A" } }, // 过滤条件
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } }, // 分组并计算总和
{ $sort: { total: -1 } } // 按总和降序排序
]);本题详细解读
1. $match 阶段
$match 阶段用于过滤文档,类似于 SQL 中的 WHERE 子句。在这个例子中,我们只选择 status 字段为 "A" 的文档。
{ $match: { status: "A" } }2. $group 阶段
$group 阶段用于将文档分组,并对每个组进行聚合操作。在这个例子中,我们按 cust_id 字段进行分组,并计算每个组的 amount 字段的总和。
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } }_id: "$cust_id":指定分组的字段。total: { $sum: "$amount" }:计算每个组的amount字段的总和,并将结果存储在total字段中。
3. $sort 阶段
$sort 阶段用于对结果进行排序。在这个例子中,我们按 total 字段进行降序排序。
{ $sort: { total: -1 } }total: -1:表示按total字段降序排序。如果要升序排序,可以使用1。
4. 完整聚合管道
将上述阶段组合在一起,形成一个完整的聚合管道。MongoDB 会依次执行每个阶段,最终返回处理后的结果。
db.collection.aggregate([
{ $match: { status: "A" } },
{ $group: { _id: "$cust_id", total: { $sum: "$amount" } } },
{ $sort: { total: -1 } }
]);这个聚合操作会返回一个包含 cust_id 和 total 字段的文档列表,按 total 字段降序排列。