With the following data:
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 } );
I would like to compute the total sum per user_ids and per date also counting the sum of the previous rows. Using the aggregation framework here is what I have so far:
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 }
}
]
)
Resulting in the following:
{ "_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 }
However I would like to compute the sum based on previous sum value. Here is what I would like to have:
{ "_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
How can I do that either using the aggregation framework, map/reduce or any new suggestions?