MongoDB Querying the date range of the past hour

I am trying to write a MongoDB query that will return data an hour ago. There is a column timewith timestamps ( "time" : NumberLong("1471953787012")), and it looks like this in SQL:

select name from table
where time between (NOW() - INTERVAL 1 HOUR) AND (NOW())

How do I write a MongoDB query to find a date range from one hour ago? I am trying with a function new Date(), but it does not work. Does anyone know what I'm doing wrong?

db.coll.find({ 
  "time" : { 
    $lt: new Date(), 
    $gte: new Date(new Date().setDate(new Date().getDate()-1))
  }   
})
+6
source share
2 answers
db.entity.find({ $and:[
    {
    "timestamp": {
        $gte: new Date(ISODate().getTime() - 1000 * 60 * 60)
    }}, 
    { 
    "timestamp": {
        $lte: ISODate()
    }}
]})

Hope this helps ...

+8
source
db.coll.find({
    "time": { // 60 minutes ago (from now)
        $gte: new Date(ISODate().getTime() - 1000 * 60 * 60)
    }
})
+3
source

Source: https://habr.com/ru/post/1652715/


All Articles