I have been working on setting up a cron job to synchronize my documents. The goal is for the job to attempt syncing a specified number of times, but only after waiting at least 2 hours since the last attempt. Each document has a "lastSyncAt" field that I can utilize for this purpose.
{
"_id" : ObjectId("628d8c4ddb65027a2cfd1019"),
"calculatedAt" : "",
"count" : 0,
"createdAt" : "2022-05-25 01:54:21",
"lastSyncAt" : "2022-05-25 03:54:21"
}
Now, I am seeking guidance on how to proceed with this task.
Should I retrieve the value of lastSyncAt in the pipeline and calculate the time difference between it and the current date? How can I extract only the hour portion from this calculation within my pipeline?
Or perhaps I should convert lastSyncAt to Unix format, get the current date in Unix format, subtract them, divide by 7200, and then check if the result is over 2 hours?
Do you recommend a different approach altogether?
I am uncertain about which path to take and would appreciate your insights on how best to tackle this challenge.
Thank you!
Update: With help from @derek-menénedez, I have successfully implemented the following solution:
[
// 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
}
}
}
]