mongodb中arggregate如何做sum,求mongodb高手
发布于 11 年前 作者 romboo 18714 次浏览 最后一次编辑是 8 年前

数据结构如下: { _id: ObjectId, items: [ {amount: Number, date: Date} ] }

现在要统计指定_id下,items.date在某个时间范围内的amount总和,并且我想用一条语句统计多个时间段的总和,期望的结果大致是:

今天:100 本周:9482 本月:11930 本年:1403820

4 回复

上周刚看了aggregate, 好像先用 projection 把数组打开,再加起来。

是用 $unwind

数据如下:

/* 0 */ { "_id" : ObjectId(“51a9e1d168590303d0b1038f”), “items” : [{ “amount” : 10 }] }

/* 1 */ { "_id" : ObjectId(“51a9e1fa68590303d0b10390”), “items” : [{ “amount” : 20 }, { “amount” : 15 }, { “amount” : 30 }] }

/* 2 */ { "_id" : ObjectId(“51a9e20c68590303d0b10391”), “items” : [{ “amount” : 11 }, { “amount” : 12 }, { “amount” : 16 }] }

db.product.aggregate( { $unwind: “$items” }, { $project: { _id:0, amount: “$items.amount”} }, { $group: { _id:null, count: {$sum:"$amount"} } }) { “result” : [ { “_id” : null, “count” : 114 } ], “ok” : 1 }

结果是 114

$unwind 把数组打开

$project 选择变量,给变量改名

$group 组合,做数学运算

回到顶部