Querying MongoDB using aggregation to find documents with a specific date range difference

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
                    }

                }
            }
        ]

Answer №1

If you're looking to achieve specific results, consider using the aggregation framework:

Experiment by eliminating projections in the example to confirm hour counts.

The $dateFromString operator can assist in converting strings to dates.

Utilize the $dateDiff operator to calculate the difference between two dates.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

React Native Header Icon Not Showing on the Left Side

I'm brand new to react and currently working on a project where navigation is done through a hamburger menu. I haven't encountered any errors in my code, but for some reason, the hamburger menu icon isn't displaying as expected. Interestingl ...

Continuous updates triggered by mouse movement with jQuery

Can someone help me figure out why my custom description isn't following my mouse pointer during the 'mousemove' event on an image? I've provided the HTML code below: <!DOCTYPE html> <html lang="en> <head> ...

Removing a value from a nested object in MongoDB

I'm working with a Mongo collection that includes a document and a nested object detailing the collections the document is in along with when it was added. I want to remove key-value pairs from the nested object based on a certain condition, for insta ...

Express 3 not recognizing path.join in Node version 0.10.41

Having trouble using less with Express 3 as I keep encountering an error "TypeError: Arguments to path.join must be strings" This error occurs in node v0.10.41 Here is a snippet of my application code: app.use(less({ src : path.join(__dirname, &a ...

Passing string values to an onClick event listener in Javascript is similar to how it is done in an onclick event listener in HTML

render() { return ( <div> <div onClick={() => "FSR.launchFeedback('ax9sgJjdSncZWoES6pew6wMIyCgSXpC')" } /> </div> ); } This piece of code initially appear ...

Tips for ensuring the child directive has finished rendering before proceeding?

I am faced with a scenario where one directive is dependent on another: <div style="border:2px solid black;height:150px;padding:10px"> <my-internal-directive></my-internal-directive> <my-internal-directive></my-interna ...

Updating an SVG after dynamically adding a group with javascript: a step-by-step guide

Currently, I am working on a circuit builder project using SVG for the components. In my HTML structure, I have an empty SVG tag that is scaled to full width and height. When I drag components from the toolbar into the canvas (screen), my JavaScript functi ...

Utilize mouseover to rotate the camera in three.js

Is it possible to utilize Three.js to rotate a camera and view an object from all angles upon hovering with the mouse? ...

Completed Animation with Callback in AngularJS CSS

Currently working with AngularJS and hoping to receive a notification upon completion of an animation. I am aware that this can be achieved with javascript animations such as myApp.animation(...), but I'm intrigued if there is an alternative method wi ...

A guide to using jqGrid: Retrieve the value of a particular cell by double clicking on a row

Is there a way to implement a feature where users can double click on any part of a row and have it open a new HTML page based on the specific content in a cell? For example, I have a table with different counties in New York listed in separate rows: Coun ...

Exploring the Possibilities of Combining Django and MongoDB

So, I've just started working on a Django 1.4 project and I've decided to use MongoDB as my backend. After spending quite some time searching on Google, I found out that mongoengine seems to be the best option since it's an active project an ...

Selecting multiple elements with the same attribute value using jQuery

I am looking to target specific DOM elements using jQuery. Below is the HTML code: <li> <span class="node> <span class="con"></span> <span class="check"></span> <img> <a title="high">abc&l ...

What issues could potentially arise from utilizing the MIME type application/json?

I'm currently developing a web service that needs to return JSON data. After doing some research, I found recommendations to use application/json. However, I am concerned about potential issues this may cause. Will older browsers like IE6+, Firefox, ...

Disabling modal popup buttons in Bootstrap 4 using Javascript

JSFiddle DEMO: https://jsfiddle.net/2yx16k8L/ I'm encountering an issue with my JS code. I want a click on a div to open the entire content within it. However, this action is causing the modal button in the dropdown to stop working. How can I resolve ...

Expandable Grid Sections in React MUI

Is there a way to create a grid layout where items with showDefault: true are always displayed at the top, and then users can click an arrow button to expand the grid and also show the items with showDefault: false? Any suggestions on how to achieve this? ...

Is the JavaScript code not executing properly?

There seems to be an issue with this code as it's not displaying an unordered list of HTML elements as intended. I've written the script and HTML code using Sublime Text, but even after trying to run the script in Chrome's developer console ...

The ng-click directive is not functioning within a script tag

i found this piece of code HTML: <script type="text/ng-template" id="custom-footer"> <div> <table cellspacing="0" cellpadding="0" ng-controller="SearchController" style="border:solid 1px black; font-family:verdan ...

Exploring the Observable object within Angular

As I delve into learning Angular through various tutorials, I encountered a perplexing issue regarding my console displaying an error message: ERROR in src/app/employee/employee.component.ts:17:24 - error TS2322: Type 'IEmployee' is not assignab ...

Transitioning the style code from inline to the head of the document disrupts the straightforward JavaScript intended to

As I delve into the world of web development, I encountered a simple issue that has been causing me frustration for the past hour. It involves code to display the border color of a div element using an alert. The code works perfectly fine when the style is ...

Difficulty with onResize in WordPress version 4.7.2

I have been trying to show the browser window width using onResize() but I can't seem to get it to work. Despite reading numerous posts about it, the JavaScript never runs (The alert doesn't show up). The method of using onResize="dispScreenWidt ...