Home > Blockchain >  Mongodb aggregation query by date difference
Mongodb aggregation query by date difference

Time:05-25

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
                    }

                }
            }
        ]

CodePudding user response:

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

  • Related