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

80
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 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