MongoDB Date range query for past hour

久未见 提交于 2020-08-06 11:58:13

问题


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

回答1:


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

Hope this helps...




回答2:


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


来源:https://stackoverflow.com/questions/39184546/mongodb-date-range-query-for-past-hour

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!