0

I am trying to make a mongo query that returns all active listings based on $currentDate

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

but it returns nothing but if I set the end_time:{$gte to {$lte ALL listings display so there must be something wrong

I'm putting the dates in the DB with 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 })
}

im thinking that it may be getting messed up when adding seconds to the end time but am not certain

and here's a copy of a DB document

{
  "_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"
  }
}
1
  • $currentDate is used to update documents, you cannot use it in queries. Commented Sep 15, 2021 at 6:31

1 Answer 1

1
db.collection.find({
  $and: [
    {
      "start_time.date": {
        $lte: new Date()
      }
    },
    {
      "end_time.date": {
        $gte: new Date()
      }
    }
  ]
})

Here working example

Note: Make sure the datatype of start_time.date and end_time.date is Date not String

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! @chandan I see it working on the playground but not on my project could it be how I am inputting the js dates?
its the javascript code above ``` setFieldValue('start_time', { date: new Date() })``` I think somehow mongo isnt parsing it to ISODate
@dovigz share the setFieldValue implementation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.