1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| db.orders.aggregate([ {$group: { _id:null, //将整个表做汇总 total: {$sum: "$total"} //total自定义的,"$total"才是数据的字段 } } ]) // 结果 { "_id" : null, "total" : NumberDecimal("44019609") }
db.orders.aggregate([ // 步骤1:匹配条件 { $match: { status: "completed", orderDate: { $gte: ISODate("2019-01-01"), $lt: ISODate("2019-04-01") } } },
// 步骤二:聚合订单总金额、总运费、总数量 { $group: { _id: null, total: { $sum: "$total" }, shippingFee: { $sum: "$shippingFee" }, count: { $sum: 1 } } },
{ $project: { // 计算总金额 grandTotal: { $add: ["$total", "$shippingFee"] }, count: 1, _id: 0 } } ])
// 结果: // { "count" : 5875, "grandTotal" : NumberDecimal("2636376.00") }
|