I am looking to track the cumulative number of shops over the past 12 months.
Sample Collection
{
_id: '5f3d4e5e01e06f0007335233',
name: 'Walmart',
createdAt: '2020-08-22T17:42:09.908+00:00'
}
Currently, I am able to retrieve the results for new shops opened in the past 12 months.
Shop.aggregate([{
$match: {
createdAt: {
$gte: {
$date: {{moment.utc().subtract(12, "months").startOf('day').toISOString()}}
},
$lt: {
$date: {{moment.utc().startOf('day').toISOString()}}
}
},
}
}, {
$project: {
dateParts: {
$dateToParts: { date: '$createdAt' }
},
total: true,
}
}, {
$group: {
_id: {
month: '$dateParts.month',
year: '$dateParts.year',
},
numShops: { $sum: 1 },
}
}])
The above query provides the number of new shops for the past 12 months. However, I need a query that gives me the total number of shops up until a specific month.
The expected result from the query should look something like this:
[{
date: 'Aug-2020',
numShops: 100, // Total number of shops until Aug-2020
}, {
date: 'Sep-2020'
numShops: 230, // Total number of shops until Sep-2020
}, ....
]