如何计算mongodb中的时间戳差异(以小时为单位)?
问题描述:
这是我的数据:
[
{
id: 1,
starttime: ISODate("2015-08-24T00:00:00.000Z"),
endtime: ISODate("2015-08-24T07:00:00.000Z")
},
{
id: 2,
starttime: ISODate("2015-08-24T20:00:00.000Z"),
endtime: ISODate("2015-08-25T01:00:00.000Z")
}
]
我可以进行mongodb查询以显示开始时间和结束时间的持续时间(在这种情况下为差异操作),结果如下:
can I make a mongodb query to display duration (or in this case a difference operation) of starttime and endtime with results like:
[ {id:1, duration: 7}, {id: 2, duration: 5}]
请注意,时间戳记可以具有不同的日期,因此$hour
(聚合管道)可能不起作用.有人可以帮忙吗?谢谢
Notice that timestamp can have different date so $hour
(aggregation pipeline) might not work. Can anyone help ? Thank you
答
db.collectionname.aggregate([
{$project: {
duration: {$divide: [{$subtract: ["$endtime", "$starttime"]}, 3600000]}
}}
])