1

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?

Pierre-Louis Gottfrois
  • 17,561
  • 8
  • 47
  • 71
  • For people in my case, here is the first *useful* piece of information coming from comments: http://stackoverflow.com/questions/16191125/mongodb-aggregation-compute-running-totals-from-sum-of-previous-rows – Pierre-Louis Gottfrois Sep 22 '14 at 15:37
  • Asya says it can't be done. She's works for mongodb, she should know :) – Sergio Tulentsev Sep 22 '14 at 17:36
  • Asya's right. It wasn't possible with aggregation in MongoDB at that time and it still isn't possible. Use map/reduce or store cumulative information on the docs or in another collection. – wdberkeley Sep 22 '14 at 19:18
  • any guide lines using map/reduce? I have no clue on how you can get the "previous" sum :-/ – Pierre-Louis Gottfrois Sep 22 '14 at 19:34

0 Answers0