Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB Date range query for past hour

I'm trying to write MongoDB query which will be return data from one hour ago. There is a column time with timestamps ("time" : NumberLong("1471953787012")) and this is how it looks 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'm trying with new Date() function but it doesn't 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))
  }   
})
like image 474
corry Avatar asked Aug 27 '16 18:08

corry


People also ask

How do I query a date in MongoDB?

We can use date () command to get a date as a string in a query without the new keyword or MongoDB shell.

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.

How do I sort time in MongoDB?

We can also use the aggregate method to sort the date and timestamp field in MongoDB. We need to pass -1 or 1 value with the date field to sort the data. If we pass -1 value with date field our result shows in descending order, if we pass 1 value with date field our result shows in ascending order.


2 Answers

db.entity.find({ $and:[
    {
    "timestamp": {
        $gte: new Date(ISODate().getTime() - 1000 * 60 * 60)
    }}, 
    { 
    "timestamp": {
        $lte: ISODate()
    }}
]})

Hope this helps...

like image 137
Reyan Chougle Avatar answered Sep 24 '22 06:09

Reyan Chougle


db.coll.find({
    "time": { // 60 minutes ago (from now)
        $gte: new Date(ISODate().getTime() - 1000 * 60 * 60)
    }
})
like image 32
Vora Ankit Avatar answered Sep 22 '22 06:09

Vora Ankit