Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

178
Visualizações
MongoDB Count By Current Month

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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();
about 4 years ago · Juan Pablo Isaza Relatório

0

You can use the Moment library.

const moment = require("moment");

const firstdate = moment().startOf('month').format('DD-MM-YYYY');
console.log(firstdate);

const lastdate=moment().endOf('month').format("DD-MM-YYYY"); 
console.log(lastdate);

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda