Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mongoose aggregate to filter data

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Every thing is fine except the start and end date

start and end date which you calculated is in string format shown below

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);

console.log({start, end})

You can update the code to get the required format for the mongodb createdAt field

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);
    console.log(new Date(start).toISOString())
    console.log(new Date(end).toISOString())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading