Hi, I’m pretty new to mongodb aggregate. I’m trying to graph the number of orders that I have by the date the order was created, but I would like to be able to includes dates that have no orders and have orders be equal to 0 on those days. Since these dates technically don’t exist, I’ve been been struggle to do this. I was wondering if there was a way to add/create these dates in mongodb aggregate. Below, I have included what I have so far. I would really appreciate any help or guidance on how to solve this. Thank you!
orderRouter.get(
'/summary',
isAuth,
isAdmin,
expressAsyncHandler(async (req, res) => {
const dailyOrders = await Order.aggregate([
{
$group: {
_id: { day: {$dateToString: {
format: '%m-%d-%Y',
date: '$createdAt' },
},
},
orders: { $sum: 1},
},
},
{ $sort: { _id: 1 } },
{$project: {
day: {
$cond:{
if:{$exist: true},
then: {dy: {$dateToString:{
format: '%m-%d-%Y',
date: '$_id.day' },
},
else: {$add:[{$first:'$dy'}, 2*24*60*60000]}
},
},
},
orders: '$orders'
}},
]);
res.send({ dailyOrders });
})
);
What I originally had:
orderRouter.get(
'/summary',
isAuth,
isAdmin,
expressAsyncHandler(async (req, res) => {
const dailyOrders = await Order.aggregate([
{
$group: {
_id: { $dateToString: { format: '%m-%d-%Y', date: '$createdAt' } },
orders: { $sum: 1 },
},
},
{ $sort: { _id: 1 } },
]);
res.send({ dailyOrders });
})
);