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))
}
})
We can use date () command to get a date as a string in a query without the new keyword or MongoDB shell.
In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.
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.
db.entity.find({ $and:[
{
"timestamp": {
$gte: new Date(ISODate().getTime() - 1000 * 60 * 60)
}},
{
"timestamp": {
$lte: ISODate()
}}
]})
Hope this helps...
db.coll.find({
"time": { // 60 minutes ago (from now)
$gte: new Date(ISODate().getTime() - 1000 * 60 * 60)
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With