Accessing MongoDB documents that are just 24 hours old

Currently, I am attempting to retrieve the previous day's documents from MongoDB by utilizing a bash script along with JavaScript.

I have successfully employed JS to send the query to MongoDB. However, I encountered an issue when handling the date format. The date retrieved appears like this:

2015-7-3 6:2:00

In my database, the records are formatted as follows:

2015-07-03 06:02:00

var d = new Date();
db.mycoll.find({ "requestedDateTime" : { $gte :d.getFullYear()+'-'+(d.getUTCMonth() + 1)+'-'+(d.getDate() - 1)+' 06:00:00' }});

The above snippet demonstrates how the query is executed at present. It's crucial that this operation occurs daily within the cronjob schedule. Moreover, if there exists an alternative method that does not require the use of JavaScript, I would be keen on exploring those options as well.

Answer №1

To calculate dates, utilize date math

var today = new Date(),
    yesterday = new Date( today.valueOf() - ( 1000 * 60 * 60 * 24 );

You can also round to the start of day in UTC:

var date = new Date(),
    today = new Date( date.valueOf() - ( date.valueOf() % ( 1000 * 60 * 60 * 24 ) ) ),
    yesterday = new Date( today.valueOf() - ( 1000 * 60 * 60 * 24 ) );

Then include it in the query:

db.mycoll.find({ "requestedDate": { "$gte": yesterday, "$lt": today } });

This will either be 24 hours from the current time or 24 hours from the previous day's time. Choose based on your preference.

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

Tips for eliminating blank rows from _POST following a PHP and JQuery post

My AJAX jQuery post is working fine, but the result looks like this: Array ( [facdatas] => Array ( [0] => Array ( [mbr_id] => 26 ) [1] => Array ( ...

How can we use jQuery to compare two blocks and set them to have the same height value?

Is there a way to compare and set equal height for two blocks within the main div? <div class="main-content"> <div class="content-1"></div> <div class="content-2"></div> </div> Javascript Code: var $content1 = $(&ap ...

Failed: Protractor could not synchronize with the page due to an error saying "angular is not present on the window"

I encountered an issue with my Protractor test scripts where I started receiving an error message. Everything was working smoothly until I made some updates to a few scripts in my projects. The error occurs at the end of running the scripts. I attempted ...

Trouble with getElementsByTagName function

Utilizing the NODE JS module, I have created an HTTP server that responds with a page containing JavaScript code to embed a webpage within an <iframe>. Within this <iframe>, I am trying to access its elements using the getElementsByTagName meth ...

How to toggle a boolean variable in AngularJS when transitioning between states

Just getting started with AngularJS and trying to figure out how to tackle this issue. I have set up the following route: name: "Tracker", url: "/tracker/:period", and I have 3 distinct states for which I've created 3 separate functions to facilit ...

Leverage OnClientClick Event in Asp.net UserControl

Looking for guidance on creating a custom clientside (OnClientClick) event that can be easily subscribed to in the markup of an asp.net page, similar to a standard asp.net control. Are there any tutorials or examples available that demonstrate how to achie ...

Saving versionKey with Mongoose and Express using a POST request

I have been facing an issue while trying to save a number and some string values to a MongoDB. Even though the code seems perfectly fine to me, doesn't show any errors, and successfully creates an entry in the database, all I get back is just a versio ...

When the file is active on a local machine, the bot commands run smoothly. However, these commands do not execute on a remote

Lately, while working on coding a discord bot using discord.js, I came across an issue. Whenever I run my bot on my local machine, all the commands work perfectly fine. However, after committing and pushing the code to GitHub, and then allowing buddy.works ...

What is the best method for displaying a field nested within an object in MongoDB?

I am currently practicing using the "sample_mflix" database provided by MongoDB Atlas and the MongoDB VS Code extension. Here is my code snippet: use('sample_mflix'); db.movies.aggregate([ { $lookup: { from: 'comments', ...

How can I show PHP retrieved data in separate text areas?

Struggling to retrieve values from the database? Simply select an employee ID using the 'selectpicker' and watch as the corresponding name and salary are displayed in the textarea. So far, I've managed to set up the following HTML Code: &l ...

Warning: Potential unhandled promise rejection in React class component

I'm trying to implement a promise inside a class so that depending on whether it resolves or rejects, another method of my component is executed. Below is the code I have: var promise = new Promise((resolve, reject) => { let name = 'DaveA&ap ...

Having trouble with AES decryption on my nodeJS/ExpressJS server backend

Looking to decipher data post retrieval from mongoDb. The retrieved data comprises encrypted and unencrypted sections. app.get("/receive", async (req, res) => { try { const data = await UploadData.find(); const decryptedData = data. ...

Tips on sending multiple files using RMongo

Following the guidelines found at http://docs.mongodb.org/manual/reference/method/db.collection.insert/ I am looking to upload a batch of multiple documents in a single RMongo::dbInsertDocument call. data = data.frame(A=c(1,2), B=c(3,4)) L = lapply(s ...

Unable to retrieve element by ID from an external source

I've been attempting to conceal a div after submitting a form, but unfortunately, I have not been successful. I am curious about the process of creating a div when utilizing an external JavaScript file. Here is the code to consider: HTML: <!DOCTY ...

Is there a way to disable default tooltips from appearing when hovering over SVG elements?

Looking for a way to display an interactive SVG image on an HTML page without default tooltips interfering. While I'm not well-versed in javascript/jQuery, I've managed to implement customized tooltips using PowerTip plugin. However, these custom ...

The Material UI autocomplete unexpectedly closes on click instead of displaying a popover as intended

I'm facing a challenge with adding a button to the Material UI autocomplete using the renderOption prop. I added a button to each row that was intended to display a PopOver component, but when clicking on the button, it automatically closes the autoco ...

What method does the framework use to determine the specific API being accessed?

How can the framework determine which API is being accessed? app.get('/user/:userId/name/export', function (req, res) { var userId = req.params.userId; } app.get('/user/:userId/name/:name', function (req, res) { var userId = req ...

Looking for advice on using the ternary operator in your code? Let us

In my JS file, the code $scope.button = id ? "Edit" : "Add"; is functioning correctly. I am trying to implement it in the View like this: <button name="saveBtn" class="btn btn-primary" tabindex="10">{{person.id ? 'Edit' : 'Add&ap ...

Renaming personalized elements in Aurelia templates

My inquiry pertains to the process of aliasing custom elements and integrating them into aurelia's html-templates. To set the scene, I am utilizing the latest webpack typescript skeleton available at https://github.com/aurelia/skeleton-navigation and ...

Bundling extraneous server code in client rollup

Can someone help me understand why the following code is being included at the top of my browser bundle by Rollup? It seems like these references are not used anywhere from my entry point. Could it be default includes from node builtins? import require$$0$ ...