I have a MondoDB aggregation pipe that outputs the daily amount of revenue by aggregating all Sales:
Sale.aggregate
([
{
$project: {
day: { $substr: ['$createdAt', 0, 10], },
},
},
{
$group: {
_id: '$day',
earnings: { $sum: '$pricing.earnings' },
},
},
{
$sort: {
_id: 1
}
},
{
$project: {
date: '$_id',
earnings: '$earnings',
},
},
{
$group: {
_id: null,
stats: { $push: '$$ROOT' },
}
},
{
$project: {
stats: {
$map: {
// returns an array with all dates between 2 provided params
input: dates.daysArray(dates.getDay(user.createdAt), dates.today()),
as: 'date',
in: {
$let: {
vars: { index: { $indexOfArray: ['$stats._id', '$$date'] } },
in: {
$cond: {
if: { $ne: ['$$index', -1] },
then: { $arrayElemAt: ['$stats', '$$index'] },
else: { _id: '$$date', date: '$$date', earnings: 0 }
}
}
}
}
}
}
}
},
{
$unwind: '$stats'
},
{
$replaceRoot: {
newRoot: '$stats'
}
},
{
$project: {
_id: 0,
x: '$date',
y: '$earnings',
},
},
])
The output of this pipe might look like this:
[
{
x: '2019-01-09',
y: 10,
},
{
x: '2019-01-10',
y: 5,
},
{
x: '2019-01-11',
y: 20,
}
]
That means on 2019-01-09 there were sales with the amount of $10, on 2019-01-10 $5, etc.
Now, I don't want the daily earnings, but the sum of all earnings ever made. That means the result should look like this:
[
{
x: '2019-01-09',
y: 10, // a total of $10 on the first day
},
{
x: '2019-01-10',
y: 15, // a total of $15 on the second day (10 + 5)
},
{
x: '2019-01-11',
y: 35, // a total of $35 on the third day (15 + 20)
}
]
So basically I don't want the daily amount but the growth.
P.S.: I am using this data to be displayed in a chart.