如何在mongodb中找到两个日期之间的小时差 [英] How to find the hours difference between two dates in mongodb
本文介绍了如何在mongodb中找到两个日期之间的小时差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 mongodb 中保存了以下结构的文档.
I have the documents in following structure saved in my mongodb.
用户日志
{
"_id":"111",
"studentID" : "1",
"loginTime" : "2019-05-01 09:40:00",
"logoutTime" : "2019-05-01 19:40:00"
},
{
"_id":"222",
"studentID" : "1",
"loginTime" : "2019-05-02 09:40:00",
"logoutTime" : "2019-05-02 20:40:00"
},
{
"_id":"333",
"studentID" : "2",
"loginTime" : "2019-05-02 09:40:00",
"logoutTime" : "2019-05-02 20:40:00"
}
是否可以查询 loginTime 和 logoutTime 之间的时间段的文档.eg: grater than 20 hrs
is it possible to query for documents where the period of time between loginTime and logoutTime.eg: grater than 20 hrs
mongodb 版本 = 3.4
推荐答案
你可以使用下面的聚合
db.collection.aggregate([
{ "$project": {
"difference": {
"$divide": [
{ "$subtract": ["$logoutTime", "$loginTime"] },
60 * 1000 * 60
]
}
}},
{ "$group": {
"_id": "$studentID",
"totalDifference": { "$sum": "$difference" }
}},
{ "$match": { "totalDifference": { "$gte": 20 }}}
])
您只需 $subtract
loginTime
from logoutTime
它会给你减去的时间戳,然后只是 $divide
它与 3600000
到以小时为单位获取时间.
You have to just $subtract
loginTime
from logoutTime
and it will give you the subtracted timestamp and then just $divide
it with 3600000
to get the time in hours.
这篇关于如何在mongodb中找到两个日期之间的小时差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文