Hey, there I’m trying to figure out how to get the total number of users for each user type per day. What I want is to filter all records between between two dates, then for each day I then sum the number of users for every role so the outpost looks like below
[
{
"date": "2023-04-05T01:43:51.661Z",
"role_1": 7,
"role_2":23,
"role_3":15
},
{
"date": "2023-04-06T01:43:51.661Z",
"role_1": 2,
"role_2":10,
"role_3":18
},
etc...
]
My current code is as follows
// Construct the aggregation pipeline
let pipeline: any = [];
if (params.startDate && params.endDate) {
pipeline.push(
{
$match: {
createdAt: {
$gte: new Date(params.startDate),
$lte: new Date(params.endDate)
}
}
}
);
} else {
// Condition to match either start date or end date for custom ranges where either one or both are provided
pipeline.push(
{
$match: {
$or: [
{
"createdAt": {
$gte: new Date(params.startDate)
}
},
{
"createdAt": {
$lte: new Date(params.endDate)
}
}
]
}
}
);
}
// Include only necessary fields in the result
pipeline.push({
$project: {
_id: 0, // Exclude the _id field
createdAt: 1,
role: 1,
}
});
pipeline.push({
$group: {
_id: {
role: "$role"
},
count: { $sum: 1 }
}
});
Which gives an overall total like the following:
[
{ _id: { role: 4 }, count: 16 },
{ _id: { role: 2 }, count: 6 },
{ _id: { role: 0 }, count: 1 },
{ _id: { role: 3 }, count: 6 },
{ _id: { role: 1 }, count: 2 }
]
I’m not sure how to proceed, in order to break it down per day/date to look like above