MongoDB根据前一行总和计算总和

时间:2014-09-22 14:00:15

标签: mongodb

使用以下数据:

db.points.save( { user_id: "a", created_at: ISODate('2014-11-03 14:17:00'), value: 1 } );
db.points.save( { user_id: "b", created_at: ISODate('2014-11-03 14:23:00'), value: 2 } );
db.points.save( { user_id: "a", created_at: ISODate('2014-11-03 16:45:00'), value: 3 } );
db.points.save( { user_id: "b", created_at: ISODate('2014-11-03 11:05:00'), value: 4 } );
db.points.save( { user_id: "a", created_at: ISODate('2014-11-04 17:00:00'), value: 5 } );

我想计算每个user_ids和每个日期的总和,也计算前一行的总和。到目前为止,我在这里使用聚合框架:

db.points.aggregate(
   [
      {
        $group : {
          _id : { user_id: "$user_id", month: { $month: "$created_at" }, day: { $dayOfMonth: "$created_at" }, year: { $year: "$created_at" } },
          total: { $sum: "$value" }
        }
      },
      {
        $sort : { "_id.year" : 1, "_id.month" : 1, "_id.day" : 1 }
      }
   ]
)

导致以下结果:

{ "_id" : { "user_id" : "b", "month" : 11, "day" : 3, "year" : 2014 }, "total" : 6 }
{ "_id" : { "user_id" : "a", "month" : 11, "day" : 3, "year" : 2014 }, "total" : 4 }
{ "_id" : { "user_id" : "a", "month" : 11, "day" : 4, "year" : 2014 }, "total" : 5 }

但是我想基于之前的总和来计算总和。这就是我想要的:

{ "_id" : { "user_id" : "b", "month" : 11, "day" : 3, "year" : 2014 }, "total" : 6 }
{ "_id" : { "user_id" : "a", "month" : 11, "day" : 3, "year" : 2014 }, "total" : 4 }
{ "_id" : { "user_id" : "a", "month" : 11, "day" : 4, "year" : 2014 }, "total" : 9 } # 4 + 5

如何使用聚合框架,map / reduce或任何新建议?

0 个答案:

没有答案