I’m trying to get the count of this month’s data using aggregate but it’s giving me no match found even though I have data in DB.
var month = new Date().getMonth();
var year = new Date().getFullYear();
const start = new Date(year, month, 1).setHours(0, 0, 1);
const end = new Date(year, month + 1, 0).setHours(23, 59, 59);
const data = await verificationModel.aggregate([
{
$match:{'status':{ $gt: 3, $lt:7},'createdAt': { $gt:start, $lt:end},'fename': { $ne: null }}
},
{
$facet: {
"categorizedBycasecount": [
{
$unwind: "$fename"
},
{
$sortByCount: "$fename"
},
{$limit:5},
]
}
}
]);
created a mongo playground it’s working there link
If I remove createdAt filter data is visible
3
Answers
this worked.
Every thing is fine except the start and end date
start and end date which you calculated is in string format shown below
You can update the code to get the required format for the mongodb createdAt field
I would suggest a Date library like moment.js, Luxon or Day.js. Then is would be simply like this:
A
$facet
stage with just one element does not make much sense to me, I would prefer$group