Home > OS >  Mongodb query based on current time
Mongodb query based on current time

Time:09-22

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"
  }
}

CodePudding user response:

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

  • Related