Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

256
Vistas
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?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

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();
over 4 years ago · Santiago Trujillo Denunciar

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

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda