Searching for specific values within a date range in MongoDB, focusing on particular times of the day

I am working with a basic mongodb database that includes two key fields:

date and value

In my node project using mongoose, I have the following code to retrieve readings within a specific date range:

Reading.find({
  date: {
    $gte: startDate,
    $lte: endDate
  }
}).select('value date')

Now, I have a requirement to fetch readings at a particular time of the day. While this could be implemented on the frontend, I am considering the possibility of optimizing the process at the database level.

Is there a way to achieve this type of query?

Reading.find({
  date: {
    $gte: startDate,
    $lte: endDate
  },
  $hour: {
    $gte: 18,
    $lte: 24
  }
}).select('value date')

Answer №1

If you want to utilize $expr with $hour, here is a sample code snippet to help you:

Reading.find({
    $expr: {
        $and: [
            { $gte: [ "$date", startDate ] },
            { $lte: [ "$date", endDate ] },
            { $gte: [ { $hour: { $toDate: "$date" } }, 18 ] },
            { $lte: [ { $hour: { $toDate: "$date" } }, 23 ] }
        ]
    }
}).select('value date')

Keep in mind that $hour will give you a value in the range of 0 to 23, so 23 will be the result for 23:59

Answer №2

To make your initial query work, ensure to include time information in the startDate and endDate variables.

Prior to running the query, it is recommended to set the hours on these variables for accurate results.

  let startDate = new Date(2020, 2, 15); //months from 0-11, March being 2
  let endDate = new Date(2020, 2, 15);

  startDate.setHours(20);
  endDate.setHours(24);

  const result = await Reading.find({
    date: {
      $gte: startDate,
      $lte: endDate
    }
  }).select("value date");

Example documents provided:

{
    "_id" : ObjectId("5e6e37d0b530b737e04ba937"),
    "date" : ISODate("2020-03-15T23:11:56.443+03:00"),
    "value" : "value4"
},
{
    "_id" : ObjectId("5e6e33b7be142a2bf0c8f75c"),
    "date" : ISODate("2020-03-15T21:54:15.823+03:00"),
    "value" : "value3"
},
{
    "_id" : ObjectId("5e6e33b4be142a2bf0c8f75b"),
    "date" : ISODate("2020-03-15T19:54:15.823+03:00"),
    "value" : "value2"
},
{
    "_id" : ObjectId("5e6e33b1be142a2bf0c8f75a"),
    "date" : ISODate("2020-03-15T17:54:15.823+03:00"),
    "value" : "value1"
}

Result:

[
    {
        "date": "2020-03-15T18:54:15.823Z",
        "_id": "5e6e33b7be142a2bf0c8f75c",
        "value": "value3"
    },
    {
        "date": "2020-03-15T20:11:56.443Z",
        "_id": "5e6e37d0b530b737e04ba937",
        "value": "value4"
    }
]

Adjusting for a +3 time zone, 18:54 corresponds to 21:54, and 20:11 equates to 23:11.

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 fixing View Encapsulation problem in Angular8

I have a parent component and a child component. The child component is created as a modal component. I have included the child component selector inside the parent component and set the view encapsulation to none so that it will inherit the parent compone ...

Retrieve various SVG file contents with a JavaScript/AJAX function

I am facing an issue with loading multiple SVG files asynchronously. I have created a function to accomplish this: function loadSVG(fileName){ var getSVG = new XMLHttpRequest(); getSVG.open('GET','assets/svg/'+fileName+'.svg&a ...

Tips for utilizing New FormData() to convert Array data from an Object for executing the POST request with Axios in ReactJs

When working on the backend, I utilize multer to handle multiple file/image uploads successfully with Postman. However, when trying to implement this in ReactJS on the frontend, I find myself puzzled. Here's a sample case: state = { name: 'pro ...

Expo: A guide on integrating expo code into an existing Android project

I'm looking to enhance my Android app (which is built in standard Java) by allowing users to create their own 3D models. To achieve this, I want to incorporate a 3D viewer within the app so that users can view and interact with their creations. My pl ...

The use of `preventDefault()` in React for the `onCopy` event is ineffective

I'm currently exploring ways to prevent the clipboard events from copying text when the onCopy event is triggered. I've tried using the onCopy handler and e.preventDefault() method, but the text is still being copied without any issues. What am I ...

What is the best way to display all filtered items in PyMongo?

I'm relatively new to the world of programming and currently facing a challenge with filtering my MongoDB data in order to display all the retrieved elements. When retrieving a single element, I don't encounter any issues. c = db.get_collection ...

Create a VueJS/VuetifyJS implementation inspired by the WhatsApp swipe between tabs animation

Currently, I am utilizing the VuetifyJS framework for VueJS and I am interested in replicating the swipe between tabs transition seen in WhatsApp for Android. In WhatsApp, you have the ability to swipe left or right to view a new section as you swipe. Vue ...

Utilize an A-frame conditional statement to check a variable and dynamically display various glTF models depending on its value

Is it possible to use JavaScript and A-frame () to create a scenario like this? I want to have an onload function named load() that will evaluate the value of variable x. If x is equal to one, I want the gltf with the ID of 1 to be visible while hiding th ...

Tips for accessing the parent reference while binding using the .on() method

I needed to attach an event like this $("div").on("click", "li",function() { var div= $(this).parent().parent(); //this is what i'm using //..... }); above the <div> <ul> <li>1</li> <li>e2</l ...

Remove the array element if the value is blank

I have an array with different objects, and I need to efficiently delete the entries where the name is empty, similar to the first and third object in the example below: var myArray = [ { "Name": "", "Value": "" }, { "Name": "aaa", "Value": "bbb" ...

Obtain the computed style by utilizing setTimeout for effective functionality

I want to retrieve the calculated style (background-color) of a span element. Here's my HTML code, consisting of two label elements, each containing an input and a span: <label> <input type="radio" name="numbers" value="01" checked/> ...

Is there a way to enclose a mention within a unique span tag after highlighting it? Similar to how tags are implemented on platforms such

Currently utilizing an AngularJS plugin called ment.io for incorporating mentions. However, I am having difficulty figuring out how to customize the appearance of the selected mention. For example, in Stackoverflow: https://i.sstatic.net/bZrkh.png Or i ...

Attempted to create registrations for two views using the identical name RCTScrollView

Having trouble running my React Native app on iOS, I keep getting an error while the Android version works perfectly fine. Does anyone have any insight on this issue? XCode 11.5, RN 0.61.5, Using React Native CLI I've searched multiple sites but hav ...

Eliminate the div element using jQuery if it contains a line break tag but no text

I am faced with a situation on a page where some div elements contain content while others only have a BR tag. I am attempting to remove the div elements that contain only the BR tag. Below is the HTML format in question: Here is an example of one type: ...

Detecting Specific Web Browsers on My Website: What's the Best Approach?

My website is experiencing compatibility issues with certain browsers, such as Firefox. I want to display a message when users visit the webpage using an unsupported browser, similar to how http://species-in-pieces.com shows a notification saying "Works ...

Detecting coordinates (x, y) on a canvas

I'm currently working on a mini-game and encountering an issue with the player movement around the green square. My character seems to be unable to move past the x, y coordinates of the square, even though it can approach it closely. I would really ap ...

Encountering the "ERPROTO" error message while attempting to send an Axios request from my REST API

I have set up my API at "localhost:3000/api/shopitems" and it successfully returns the JSON data below when accessed through a browser: [ { "item_available_sizes": { "s": 1 }, "imgs": { "album": [], ...

Grouping elements of an array of objects in JavaScript

I've been struggling to categorize elements with similar values in the array for quite some time, but I seem to be stuck Array: list = [ {id: "0", created_at: "foo1", value: "35"}, {id: "1", created_at: "foo1", value: "26"}, {id: "2", cr ...

Fill input text fields with values based on dropdown selection and start with 2 input fields pre-filled

Initially, the issue is that there are 2 input text fields displayed. Depending on the selection from a drop-down menu ranging from 2 to 6, additional input fields should be added or removed. Here's my code: function addElements(selectElement) { va ...

Leveraging the Scroll feature in Bootstrap for smooth scrolling

Seeking assistance with implementing scroll in Bootstrap 5 on my child component (ProductList.vue). Can anyone guide me on how to integrate the code? I have been searching for a solution without success. Below is the Bootstrap 5 code on the child component ...