【发布时间】:2021-08-07 09:41:02
【问题描述】:
每当用户登录时,我都会尝试根据 mongoDB 中的数据计算用户的登录时间。我有登录 startDateTime , endDateTime 和 duration 字段,但如果持续时间为 0 则它应该采用当前日期时间和 startDateTime 的差异。
我在这里遇到的问题是结果错误,因为我已经通过使用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")
}
注意:我已经通过减去整数来检查它是否准确,所以我认为我的查询没问题
【问题讨论】:
标签: javascript mongodb datetime mongoose logging