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

297
Vistas
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 Respuestas
Responde la pregunta

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