0

I am using MongoDB 4.2, the collection is the following:

{ "_id" : 1, "group_id": 1, "amount" : 10 }
{ "_id" : 2, "group_id": 1, "amount" : -5 }
{ "_id" : 3, "group_id": 1, "amount" : 8 }
{ "_id" : 4, "group_id": 2, "amount" : -1 }
{ "_id" : 5, "group_id": 2, "amount" : 7 }
{ "_id" : 6, "group_id": 2, "amount" : -2 }
{ "_id" : 7, "group_id": 3, "amount" : 10 }
{ "_id" : 8, "group_id": 3, "amount" : 15 }

How can i create a running sum of the documents?

EXPECTED RESULT:

Note1 : The documents must be filtered by _id giving a range for example between _id:2 and _id:7.

The result should be the following:

{ "_id" : 2, "group_id": 1, "total_amount" : -5 }
{ "_id" : 3, "group_id": 1, "total_amount" : 3 }   // (it was 8 but summing the previous -5 + 8 (current) = 3
{ "_id" : 4, "group_id": 2, "total_amount" : -1 }
{ "_id" : 5, "group_id": 2, "total_amount" : 6 }   // (it was 7 but summing the previous -1 + 7 = 6
{ "_id" : 6, "group_id": 2, "total_amount" : 4 }   // (it was -2 but summing the previous 6 - 2 = 4
{ "_id" : 7, "group_id": 3, "total_amount" : 10 }

Note2: The running sum must deal with group_id and sort by _id (the sort is important for summing of course) I should only sum documents with the same group_id (ordered by _id)

Dail
  • 4,622
  • 16
  • 74
  • 109
  • Looks like https://stackoverflow.com/questions/38957649/compute-first-order-derivative-with-mongodb-aggregation-framework. Although I there are better way to do this today. – styvane Apr 17 '20 at 18:01
  • @styvane Can you explain? what are the other ways? – Dail Apr 17 '20 at 18:27

0 Answers0