【问题标题】:How to calculate timestamp difference in mongodb (in hours)?如何计算 mongodb 中的时间戳差异(以小时为单位)?
【发布时间】:2021-08-12 18:15:11
【问题描述】:

这是我的数据:

[
   {
       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 查询来显示 starttime 和 endtime 的持续时间(或者在这种情况下是差异操作),结果如下:

[ {id:1, duration: 7}, {id: 2, duration: 5}]

请注意,时间戳可以有不同的日期,因此$hour(聚合管道)可能不起作用。任何人都可以帮忙吗?谢谢

【问题讨论】:

  • 您可以使用带有 $substract 的投影:{$project: {_id:'$id', duration : {$subtract : ['$endtime', '$starttime']}}},
  • 试过了,结果:[{id:1, duration: null}, {id: 2, duration: null}]
  • 抱歉,我的变量名不正确,$subtract 有效,结果如下:[{id: 1, duration:25200000}, {id:2, duration:18000000}]。这是几秒钟后?
  • 以毫秒为单位
  • 持续时间:{$divide: [{$subtract: ["$endtime", "$starttime"]}, 3600000]},谢谢!

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:
db.collectionname.aggregate([
  {$project: {
      duration: {$divide: [{$subtract: ["$endtime", "$starttime"]}, 3600000]}
  }}
])

【讨论】:

【解决方案2】:

Mongo 5.0 开始,$dateDiff 聚合运算符非常适合您产生两个日期之间差异的用例:

// { _id: 1, start: ISODate("2015-08-24T00:00:00Z"), end: ISODate("2015-08-24T07:00:00Z") }
// { _id: 2, start: ISODate("2015-08-24T20:00:00Z"), end: ISODate("2015-08-25T01:00:00Z") }
db.collection.aggregate([
  { $project:
    { duration:
      { $dateDiff: { startDate: "$start", endDate: "$end", unit: "hour" } }
    }
  }
])
// { "_id" : 1, "duration" : 7 }
// { "_id" : 2, "duration" : 5 }

【讨论】:

    【解决方案3】:

    这对我有用。

    const start_time = "2021-08-10T16:25:46.191Z",
     end_time = "2021-08-10T20:25:46.191Z"
    
    const total = new Date(end_time).getTime() -  new Date(start_time).getTime();
      const hours = (Math.floor((total)/1000))/3600;
    console.log(hours);
    
    

    【讨论】:

    • 这个问题是关于 MongoDB,而不是一般的 JavaScript。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 2016-07-21
    • 1970-01-01
    • 2017-02-21
    相关资源
    最近更新 更多