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

87
Vistas
Mongoose how to count unique days in a month?

i am working on a problem where in my database there supposed to be multiple entries from day to day. each entry includes a timestamp. the problem is im supposed to find how many days in each month a data has been entered. ex: if a user sends a message every 2 days in may. my answer would be: "the user used the message function for 15 days in may". now if the user sends 5 messages every 2 days in may. the answer would be still 15. im only counting the days the user has been using the app.

using this query:

model.find({ 
    date: {
        $gte: new Date(startOfMonth), 
        $lt: new Date(endOfMonth)
    }
})

i was able to find all data entries on a specific month. the data may look like something like this:

 Date: dd/mm/yy        Message:
 1/5/2022              "Hello"
 1/5/2022              "World"
 1/5/2022              "!"
 5/5/2022              "Hello World!"
 8/5/2022              "Hello World!"

the desired answer would be 3 unique days in may.

How do i achieve this using mongodb? the simplest answer that come to mind is to use additional queries to group by unique days, but i have no idea how to do that using mongo provided i need to access the date.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

This might solves your problem. it will return distinct messages.


Model.aggregate(
    [
        { "$match": {
            "date": { 
                "$gte": new Date(startOfMonth), "$lt": new Date(endOfMonth)
            }
        }},
        { "$group": {
            "_id": { 
                "year":  { "$year": "$date" },
                "month": { "$month": "$date" },
                "day":   { "$dayOfMonth": "$date" }
            }
            "count": { "$sum": 1 }
        }}
    ],
    function(err,result) {
        // do something with result

    }
);
about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use distinct
db.collection.distinct({date:{$gte:new Date(startOfMonth),$lt:new Date(endOfMonth)}}).length
if you are directly storing the date of it.

Note : This may not work if you're storing complete timestamp instead of date.

about 4 years ago · Juan Pablo Isaza 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