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

298
Visualizações
Mongodb aggregation query by date difference

I am trying to make a cron job which syncs my documents. It should try to do it x amount of times but only after 2h have passed since the last try. On each document I have "lastSyncAt" field which I can use.

{
    "_id" : ObjectId("628d8c4ddb65027a2cfd1019"),
    "calculatedAt" : "",
    "count" : 0,
    "createdAt" : "2022-05-25 01:54:21",
    "lastSyncAt" : "2022-05-25 03:54:21"
} 

How should I approach this?

Should I get the lastSyncAt value in pipeline and calculate difference between currentDate? How do I get only the hours portion of that in my pipeline?

Should I convert lastSyncAt into unix and get currentDate in unix substract them and divide by 7200 to see if it is greater than 2?

Or should I take another approach?

I'm not even sure what approach to take. Not looking for code but an idea how to handle this.

Thx

Update: Thanks to @derek-menénedez I managed to get it working as shown below:

[
            // Stage 1
            {
                $addFields: {
                    lastSyncAt: {
                        $dateDiff: {
                            startDate: {$dateFromString: {
                                    dateString: "$lastSyncAt",
                                    timezone: "Europe/Zagreb"
                                }},
                            endDate: "$$NOW",
                            unit: "minute",
                            timezone: "Europe/Zagreb"
                        }
                    }
                }
            },

            // Stage 2
            {
                $match: {
                    lastSyncAt: {
                        $gt: 120
                    }

                }
            }
        ]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use the aggregation framework to achieve the things that you want:

https://mongoplayground.net/p/1RzPCYbeHEP

You can try to remove the projection on the example to validate the number of hours.

$dateFromString operator helps you to create a date from a string

$dateDiff operator helps you to extract the diff of two dates

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