Search code examples
node.jsmongodbmongoose

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


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