I have a collection of ProductViews
.
ProductView
{
productId: '5b8c0f3204a10228b00a1745,
createdAt: '2018-09-07T17:18:40.759Z',
}
And I have a query for fetching the daily views for a specific product.
Query
ProductView.aggregate([
{ $match: { productId } },
{ $project: { day: { $substr: ["$createdAt", 0, 10] } } },
{
$group: {
_id: "$day",
count: { $sum: 1 },
time: { $avg: "$createdAt" },
}
},
{ $sort: { _id: 1 } },
{
$project: {
date: '$_id',
views: '$count',
},
},
]).exec((err, result) => ...)
Current Results
[
{ date: '2018-09-01', views: 1 },
{ date: '2018-09-02', views: 3 },
{ date: '2018-09-04', views: 2 },
{ date: '2018-09-05', views: 5 },
// ...
]
Issue
The issue is, that this aggregation does not return { date: '2018-09-03', views: 0 }
for days with 0
views. This results in incorrect displaying of the data:
Results should look like
[
{ date: '2018-09-01', views: 1 },
{ date: '2018-09-02', views: 3 },
{ date: '2018-09-03', views: 0 },
{ date: '2018-09-04', views: 2 },
{ date: '2018-09-05', views: 5 },
// ...
]
P.S.: It would be perfect to pass in the start and end dates to output results based on this range
See Question&Answers more detail:
os