javascript - 如何在 $group 内的 mongoDb 聚合中减去两个日期?
问题描述
我试图在用户登录时根据 mongoDB 中的数据计算用户的登录时间。我有登录和字段startDateTime
,但如果持续时间为 0,那么它应该采用当前日期时间和.endDateTime
duration
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")
}
注意:我已经通过减去整数来检查它是否准确,所以我认为我的查询没问题
解决方案
我已经通过使用$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
推荐阅读
- android - 以编程方式在android中进行通话录音
- r - 在 R 中使用 arima 循环
- asp.net - 带有域发布的 Asp.net Core Mvc Jquery 客户端信号器和 web api 核心 3.1 信号器
- javascript - 测试非无效性的惯用方法
- swift - 如何让scrollview在swift中分别滚动到它的内容高度
- reactjs - 登录的路由没有改变:firebase.auth().onAuthStateChanged
- angular - Angular 11 单元测试的 JEST 设置问题
- python - 我们可以在 django 框架上存储文件吗?
- c# - UWP获取Datagrid的ScrollViewer的垂直偏移量
- c++ - 跨不同名称空间的朋友类不起作用并且名称空间无法识别