Querying Mongodb with current time parameters

I'm attempting to create a mongo query that retrieves all active listings based on the current date

{
  $and: [
    {
      start_time: {
        $lte: {
          $currentDate: {
            $type: "date"
          }
        }
      }
    }, 
    {
      end_time: {
        $gte: {
          $currentDate: {
            $type: "date"
          }
        }
      }
    }
  ]
}

However, this query returns nothing. If I change end_time:{$gte to {$lte, all listings are displayed, indicating there may be an issue.

I'm adding the dates to the database using JavaScript

if (checked) {
  var d = new Date()
  d.setSeconds(d.getSeconds() + values.sale_price * 100)
  setFieldValue('start_time', { date: new Date() })
  setFieldValue('end_time', { date: d })
}

I suspect the problem may arise when adding seconds to the end time, but I'm not certain

Here is a sample document from the database

{
  "_id": {
    "$oid":"61401b66t4e445t5j43j748e"
  },
  "name": "test",
  "sale_price": {
    "$numberInt": "5000"
  },
  "start_time": {
    "date": "2021-09-14T03:47:31.918Z"
  },
  "end_time":{
    "date": "2021-09-19T22:40:51.918Z"
  }
}

Answer №1

db.collection.find({
  $and: [
    {
      "start_date": {
        $lte: new Date()
      }
    },
    {
      "end_date": {
        $gte: new Date()
      }
    }
  ]
})

Check out this live example

Note: Ensure that the data type of start_date and end_date fields is Date and not String

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

Is Turbopack compatible with frameworks other than NextJs?

With its impressive speed, it would be great to utilize it in various outdoor projects like Vite. Unfortunately, there does not seem to be much information about it on their website I also checked out https://github.com/vercel/turbo but the details were s ...

Showcasing the information stored within my li element, I am able to access and view the data through my console

I want to showcase the data in the browser Upon hitting the api call, I retrieve the data in my console. The challenge lies in displaying the data within my li tag. Below are snippets of my relevant code and the entire code can be found in the gist links p ...

Retrieve content from JSON post data

I have been facing an issue where I am trying to send a JSON file from a web page to a nodeJS server. My goal is to assign the JSON file to an object on the server side and print it out in the console. Despite researching extensively online and attempting ...

Determining the position coordinates of an element in relation to the viewport using JavaScript, regardless of its relative positioning

I am currently developing a vueJs web application and I'm in need of determining the position of an element within my web app relative to the viewport itself, rather than its parent elements. I'm curious if there exists a function or property tha ...

Executing mailto URLs from action method

As a newcomer to MVC, I am looking to create an action method in MVC that triggers Mailto:?body=body goes here.&subject=test subject, allowing the default mail client to automatically populate the user's email. Currently, I have a List<String&g ...

Ways to verify if a string is a number without using isNaN and with specified criteria

I am trying to determine if a string represents a valid number without relying on the isNaN function. The reason for this is that I need to be able to accept the ',' character, which isNaN ignores. Additionally, I do not want to allow negative nu ...

Having trouble accessing object properties fetched via API, receiving the error message "TypeError: Cannot read property '' of undefined" in Next.js with JavaScript

Encountering a unique issue specific to NextJs. Fetching data from an API using a custom hook and receiving an array of objects as the result. Successfully logging the entire result (array of objects). const myMovieGenreObjects = useFetchNavBarCategories( ...

Animation with multiple meshes in Three.js

Having just started working with threejs, I decided to use a for loop to create 400 cylinders. The rendering of the objects in the scene works perfectly. However, when it comes to animating the cylinders, only one out of the 400 seems to rotate. How can I ...

The <br/> tag is not functioning properly when retrieving text from a MySQL query

Currently, I am involved in a project that involves an A.I pushing text onto a MySQL database. Our goal is to display the ongoing writing process on a webpage. We are still actively working on this. We are retrieving the data and regularly checking the da ...

Manage a frame directly from the parent page

I am faced with a situation where I have a web page with two textboxes and a button. Unfortunately, I am unable to alter the contents of this page in any way. My goal is to find a way to automatically populate the first textbox with some text when the pag ...

What is the best way to access the second array in a JSON object?

I have successfully implemented autocomplete with JSON and PHP. It is working fine, but now I am facing a challenge in retrieving the second array from the JSON data. Below is the script I have used in source.php: <?php $req = "SELECT namaBarang, har ...

Dynamically adjust the height of a parent div to match its child div's height upon clicking using JavaScript

Within my div element (divChatContainer), there is a top div (divChatContainerTop) containing a "span" element. When this "span" element is clicked, I want the container div to resize to the height of the "divChatContainerTop" (essentially minimizing the c ...

Ways to inspect a number within a span and adjust its color depending on the value?

Can someone help me figure out why this code is not reading the value correctly? Check it out here This is the HTML: <a class="InterestLink">Click me</a> <div id="InterestExpander"> <div id="InterestExpanderX"> ...

Utilize RMongo to establish a connection to mongoDB through the method of port forwarding

I establish a connection to a mongodb server by utilizing port forwarding in the following way: ssh -i key.pem -Nf -L 27018:xx.xxx.xxx.xxx:27017 <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="314453445f45447149491f4949491f4949 ...

Angular-UI keypress event allows users to interact with components and

I am facing challenges while using the keypress feature in the following code snippet- <div ng-controller="GBNController"> ... <input id="search-field" type="text" placeholder="JSON Query" ng-model="queryText" ui-keypress="{enter: foo()}"/> .. ...

Permission Denied when trying to use a non-root user in PNPM docker command

Today, I came across pnpm and it successfully resolved the issue I was facing with npm timing out during installation, which is absolutely fantastic. However, I encountered a problem with pnpm when using it in a docker image. In the past, when using npm, ...

Setting a default value for all mongoose queries

Currently, I am struggling to develop a mongoose schema that can automatically pass a specific value in one of its fields for all calls to find() or findOne(). Despite attempting to use the 'default' property on the field declaration, it didn&apo ...

The iron-session package does not export the path ./next/dist from the package

I am encountering an issue while using iron-session. Below is the code snippet causing the error: import { withIronSessionSsr } from 'iron-session/next/dist'; ... export const getServerSideProps = withIronSessionSsr(async function ({ req, r ...

How to access class type arguments within a static method in Typescript: A clever solution

An issue has arisen due to the code below "Static members cannot reference class type parameters." This problem originates from the following snippet of code abstract class Resource<T> { /* static methods */ public static list: T[] = []; ...

Using AJAX to submit a form and retrieve response data in Javascript

After successfully getting everything to post correctly, I encountered a problem with this script. It keeps loading the content into a new page. Could it be related to the way my php file returns it using "echo(json_encode($return_receipt));"? <s ...