首页 > 解决方案 > 如何在 $group 内的 mongoDb 聚合中减去两个日期?

问题描述

我试图在用户登录时根据 mongoDB 中的数据计算用户的登录时间。我有登录和字段startDateTime,但如果持续时间为 0,那么它应该采用当前日期时间和.endDateTimedurationstartDateTime

我在这里遇到的问题是结果是错误的,因为我已经通过在浏览器控制台中使用new Date().

这是我正在尝试的聚合查询

    let queryFilter = {
    createdAt: {
      "$gte": filter.from ? new Date(filter.from) : new Date(new Date().toDateString()),
      "$lte": filter.to ? new Date(filter.to) : new Date(new Date().toDateString())
    }
  }


AgentJournal.aggregate([
    {
      $match: queryFilter
    },
    {
      $group: {
        _id: { agent: "$agent", queue: "$queue", channel: "$channel" },
        loginTime: { "$sum": { "$cond": [{ "$eq": ["$event", "LOGIN"] }, { "$cond": [{ "$eq": ["$duration", 0] }, { $subtract: [new Date(), new Date("$startDateTime")] }, "$duration"] }, 0] } },
      }
    }
  ])

这是存储在我的数据库中的示例文档:

{
    "_id" : ObjectId("608a6ee3e781511b7283c393"),
    "duration" : 0,
    "agent" : "SIP/intellicon",
    "queue" : "sales",
    "event" : "LOGIN",
    "startDateTime" : "2021-04-29 13:27:21",  //String Type
    "endDateTime" : "0000-00-00 00:00:00",    //String Type
    "channel" : "fb_pages",
    "__v" : 0,
    "createdAt" : ISODate("2021-04-29T08:31:31.995Z"),
    "updatedAt" : ISODate("2021-04-29T08:31:31.995Z")
}

注意:我已经通过减去整数来检查它是否准确,所以我认为我的查询没问题

标签: javascriptmongodbdatetimemongooselogging

解决方案


我已经通过使用$toDate@turivishal 的方法解决了这个问题,并将新日期首先转换为我的本地标准时间(即new Date().toLocaleString()),然后将其传递给$toDate(即{$toDate:new Date().toLocaleString}

现在计算登录时间的查询是

loginTime: { "$sum": { "$cond": [{ "$eq": ["$event", "LOGIN"] }, { "$cond": [{ "$eq": ["$duration", 0] }, { $subtract: [{ $toDate: new Date().toLocaleString() }, { $toDate: "$startDateTime" }] }, "$duration"] }, 0] } },

再次感谢@turivishal


推荐阅读