【问题标题】:How to subtract two date time in mongodb如何在mongodb中减去两个日期时间
【发布时间】:2018-06-30 08:47:25
【问题描述】:

我用过聚合函数。

db.checkins.aggregate([
       {$match: {checkinType: "Beacon",
               "associationIds.organizationId":"af39bc69-1938-4149",
               "checkinData.time": {"$gte": new Date("2018-01-18T18:30:00.000Z"), 
                                   "$lt": new Date("2018-01-19T18:30:00.000Z")}
                }
        },
       {"$sort":{"checkinData.time":-1}},
       {$group: {"_id":
                    {"orgId":"$asst.organizationId", "userId":"$asst.userId"},
                    "lastSeen":{"$first":"$checkinData.time"},
                   "firstSeen":{"$last":"$checkinData.time"},
               }
       }, 
      {"$project":{"_id":1,"lastSeen":1, "firstSeen":1, 
                  totalHourSpent:{$subtract: ["$lastSeen","$firstSeen"]}}}, 
  ])

当我执行此查询时,mongo 以毫秒为单位返回 totalHourSpent,如下所示。

{
  "_id" : {
        "orgId" : "af39bc69-1938-4149-b9f7-f101fd9baf73",
        "userId" : "34adb4a0-0012-11e7-bf32-cf79d6b423e9"
  },
 "lastSeen" : ISODate("2018-01-19T18:49:52.242+05:30"),
 "firstSeen" : ISODate("2018-01-19T10:08:21.026+05:30"),
 "totalHourSpent" : NumberLong("31291216")
},
{
  "_id" : {
       "orgId" : "af39bc69-1938-4149-b9f7-f101fd9baf73",
       "userId" : "679416b0-3f88-11e7-8d27-77235eb1ba9b"
   },
   "lastSeen" : ISODate("2018-01-19T20:51:30.946+05:30"),
   "firstSeen" : ISODate("2018-01-19T11:07:44.256+05:30"),
   "totalHourSpent" : NumberLong("35026690")
 },

如何以小时为单位计算 totalHourSpent。提前致谢。

【问题讨论】:

标签: node.js mongodb aggregate mlab


【解决方案1】:

$subtract 为您提供以毫秒为单位的持续时间。所以我们需要将持续时间除以 3600000 为小时格式。

返回的 Mills 可以通过除以 3600000(1 小时的毫秒数)转换为小时:

totalHourSpent:{$divide : [{$subtract: ["$lastSeen","$firstSeen"]}, 3600000]}

35026690÷3600000=9.72963611111111 hours

【讨论】:

  • 如何获取两位小数后的值。谢谢!
  • 如果您关心精度,您可能需要使用扩展的 bson 类型,例如 $numberDecimal
  • 我想要 9.729 小时
  • 从 Mongdb 4.2 起可以使用 $trunc 操作符,语法 { $trunc : [ , ] } 与聚合,见链接stackoverflow.com/questions/47038444/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多