You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MongoDB中计算起止日期时间差并拆分时分秒

MongoDB计算两个日期字段的时间差并拆分成天、时、分、秒

假设你的集合中有startDate和endDate两个日期字段,需要计算二者的时间差,并拆分为天数(days)、小时(hours)、分钟(minutes)、秒数(seconds),以下是具体实现方案:

集合记录示例

[
  {
    "startDate": {
      "$date": {
        "$numberLong": "1630926969195"
      }
    },
    "endDate": {
      "$date": {
        "$numberLong": "1648558585308"
      }
    }
  }
]

聚合查询实现

通过MongoDB的聚合管道,我们可以逐步计算并拆分时间差:

db.collection.aggregate([
  {
    $addFields: {
      // 计算两个日期的毫秒差,转换为总秒数(取整)
      totalSeconds: { $floor: { $divide: [{ $subtract: ["$endDate", "$startDate"] }, 1000] } }
    }
  },
  {
    $addFields: {
      // 计算天数:总秒数除以一天的秒数(86400)取整
      days: { $floor: { $divide: ["$totalSeconds", 86400] } },
      // 计算剩余秒数:总秒数对一天的秒数取模
      remainingAfterDays: { $mod: ["$totalSeconds", 86400] }
    }
  },
  {
    $addFields: {
      // 计算小时数:剩余秒数除以一小时的秒数(3600)取整
      hours: { $floor: { $divide: ["$remainingAfterDays", 3600] } },
      // 计算剩余秒数:剩余秒数对一小时的秒数取模
      remainingAfterHours: { $mod: ["$remainingAfterDays", 3600] }
    }
  },
  {
    $addFields: {
      // 计算分钟数:剩余秒数除以一分钟的秒数(60)取整
      minutes: { $floor: { $divide: ["$remainingAfterHours", 60] } },
      // 剩余秒数即为最终的秒数
      seconds: { $mod: ["$remainingAfterHours", 60] }
    }
  },
  {
    // 只保留需要的字段,移除中间计算字段
    $project: {
      days: 1,
      hours: 1,
      minutes: 1,
      seconds: 1,
      _id: 0
    }
  }
])

查询结果

执行上述聚合后,会得到符合需求的结果:

{
  "days": 204,
  "hours": 1,
  "minutes": 40,
  "seconds": 16
}

内容的提问来源于stack exchange,提问作者Aravinth E

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:20:29