Home > Blockchain >  MongoDB Count By Current Month
MongoDB Count By Current Month

Time:04-17

I'm new to MongoDB. I need to get the count of the posts which are posted in this current month. PlateModel is my model I've kept timestamps true also. It looks like the below:

  { timestamps: true }

My present code in the Controller looks like below:

 const today = new Date();
    const host_count = await PlateModel.find({
      $and: [
        {
          postedBy: req.user._id,
        },
        {
          createdAt: today.getMonth(),
        },
      ],
    }).count();

But, I get the count value 0. Can anyone help me to figure out the problem?

CodePudding user response:

You could filter the objects from the start of the current month to the end of the next month:

const startOfCurrentMonth = new Date();
startOfCurrentMonth.setDate(1);

const startOfNextMonth = new Date();
startOfNextMonth.setDate(1);
startOfNextMonth.setMonth(startOfNextMonth.getMonth()   1);

const host_count = await PlateModel.find({
  $and: [
    {
      postedBy: req.user._id,
    },
    {
      createdAt: {
          $gte: startOfCurrentMonth,
          $lt: startOfNextMonth
      }
    },
  ],
}).count();
  • Related