I am trying to extend the answer provided in MongoDB Charts – chart cumulative growth? to group by multiple attributes.
Basically if the data has a date and a type A, B and C. I want to get the cumulative totals of All the A's,the cumulative totals of All the B's and the cumulative totals of All the C's. I know I could do this in seperate graphs but it would be nice to create one pipeline with more dimensions of attributes. The first few parts of the pipeline I can see what to do but I need help with the map section to total up the records per type and not everything upto that date. Here is the code so far....
[
{ $addFields: { "date": { $dateToString: { format: "%Y-%m-%d", date: { $toDate: "$_id" }} }
, "document_type": "$document_type" }},
{ $group: { _id: {"date":"$date", "document_type": "$document_type"}, count: { $sum: 1 } } },
{ $sort: { _id: 1 } },
{ $group: { _id: null, days: { $push: "$_id" }, counts: { $push: "$count" } } },
{ $project: {
days: {
$map: {
input: { $range: [ 0, { $size: "$days" } ] },
in: { _id: { $arrayElemAt: [ "$days", "$$this" ] }, cumGrowth: { $sum: { $slice: [ "$counts", 0, { $add: [ "$$this", 1 ] } ] } } }
}
}
}
},
{ $unwind: "$days" },
{ $replaceRoot: { newRoot: "$days" } },
{ $sort: { _id: 1 } },
]
Can anyone please help calculate the correct cumulative totals in the map section?
Current code for this data:
Date 1-1-20, document_type = A
Date 1-1-20, document_type = B
Date 1-1-20, document_type = C
Date 1-1-20, document_type = A
Date 2-1-20, document_type = A
Date 2-1-20, document_type = B
Date 2-1-20, document_type = B
gives
date 1-1-20 type A count 2
date 1-1-20 type B count 1
date 1-1-20 type C count 1
date 2-1-20 type A count **5** <-- should be 3 but includes the B's and C's from 1-1-20
date 2-1-20 type B count **6**
Date 2-1-20, type C count **4**