I’m working on a dashboard analytics region that should be able to show the the number of user registrations for different types of users (roles) for a given time period such as “This Week”, “Last 30 days” or “this Year”. I’m working on the first one and I’ve been able to do some filtering with the following progress:
let pipeline = [];
// Default filter type
params.filter = '7days';
// params.filter = params.filter || '7days';
// Construct the aggregation pipeline
// let currentWeek = getWeek(new Date());
let currentWeek = 50;
// let currentYear = new Date().getFullYear();
// Set the time period based on the createdAt field
pipeline.push({
$project: {
year: {
$year: "$createdAt",
},
month: {
$month: "$createdAt",
},
week: {
$week: "$createdAt",
},
day: {
$dayOfWeek: "$createdAt",
},
},
});
if (params.filter === '7days') {
pipeline.push({
$match: {
// year: currentYear,
week: currentWeek,
},
});
}
pipeline.push({
$group: {
_id: "$day",
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
day: {
$switch: {
branches: [
{
case: { $eq: ["$_id", 1] },
then: "Sunday",
},
{
case: { $eq: ["$_id", 2] },
then: "Monday",
},
{
case: { $eq: ["$_id", 3] },
then: "Tuesday",
},
{
case: { $eq: ["$_id", 4] },
then: "Wednesday",
},
{
case: { $eq: ["$_id", 5] },
then: "Thursday",
},
{
case: { $eq: ["$_id", 6] },
then: "Friday",
},
{
case: { $eq: ["$_id", 7] },
then: "Saturday",
},
],
default: "Unknown",
},
},
count: 1,
},
});
Which gives an output like the following:
[{day:"Wednesday", count: 3}, {day:"Friday", count: 7}]
BUt i need to be able to set zero values by default for every other day if there is nothing to count. So for e.g. Monday will be 0 and so on. That way I will have all 7 days with a count to send to a frontend client to show a UI chart.
How can I do so?
I also plan to use this for months of the year and will figure out how to do it for everyday in the month later.