skip to Main Content

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


  1. Chosen as BEST ANSWER
     var month = new Date().getMonth();
     var year = new Date().getFullYear();
     const start = new Date(new Date(year, month, 1).setHours(0, 0, 1));
     const end = new Date(new Date(year, month + 1, 0).setHours(23, 59, 59));
      
    

    this worked.


  2. 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())
    Login or Signup to reply.
  3. I would suggest a Date library like moment.js, Luxon or Day.js. Then is would be simply like this:

    db.collection.aggregate([
       {
          $match: {
             "createdAt": {
                $gt: DateTime.now().startOf('month').toJSDate(),
                $lte: DateTime.now().plus({ months: 1 }).endOf('day').toJSDate()
             }
          }
       },
       { $sortByCount: "$name" },
       { $limit: 5 },
       {
          $group: {
             _id: null,
             categorizedBycasecount: { $push: "$$ROOT" }
          }
       }
    ])
    

    A $facet stage with just one element does not make much sense to me, I would prefer $group

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search