node.js - 如何在 MongoDB 中获取基于日期过滤器(周、月和自定义日期)的文档?
问题描述
我正在尝试根据 MongoDB 中的以下日期过滤器获取所有文档:
- 仅限本周
- 仅限上周
- 仅限本月
- 仅上个月
- 自定义日期之间。
我的收藏:
[
{
_id: "123",
status: "seen",
userId: "589",
createdAt: ISODate("2020-11-17T04:35:29.646Z"),
},
{
_id: "223",
status: "seen",
userId: "589",
createdAt: ISODate("2020-11-17T04:35:29.646Z"),
},
{
_id: "474",
status: "unseen",
userId: "589",
createdAt: ISODate("2020-11-10T04:35:29.646Z"),
},
{
_id: "875",
status: "seen",
userId: "112",
createdAt: ISODate("2020-10-11T04:35:29.646Z"),
},
{
_id: "891",
status: "unseen",
userId: "112",
createdAt: ISODate("2020-10-11T04:35:29.646Z"),
},
{
_id: "891",
status: "unseen",
userId: "113",
createdAt: ISODate("2020-11-09T04:35:29.646Z"),
}]
预期结果:
- 应用 This_Week 过滤器时 - 获取 createdAt 属于本周的所有 userId,然后计算通知百分比。
[{
userId : "589",
notificationPercentage: 100% // Because userId 589 has 2 seen documents for this week.
}]
- 应用 This_Month 过滤器时: - 本月创建了 userId 589 和 userId 113 并为其计算 notificationPercentage。
[{
userId : "589",
notificationPercentage: 66.66%
},
{
userId : "113",
notificationPercentage: 0%
}]
- 应用 Last_month 过滤器时:
[{
userId : "112",
notificationPercentage: 50% //Because only userId 112 was created in last month and finding the notification percentage for it.
}]
- 应用 Last_week 过滤器时:
[{
userId : "113",
notificationPercentage: 0% //Because only userId 113 was created in last week and finding the notification percentage for it.
},
{
userId : "589",
notificationPercentage: 0% //Because only userId 113 was created in last week and finding the notification percentage for it.
}]
通知百分比公式 -
(No of times the user has seen/no of times he got notifications) * 100
解决方案
您可能有类似以下的内容。使用匹配操作过滤掉。在此示例中,我向您展示了 last_week 的详细信息。我检查了你上面提到的所有场景。它工作正常
[{$match: {
$expr:{
$and:[
{$gt:["$createdAt",new Date(new Date()-14*60*60*24*1000)]},
{$lt:["$createdAt",new Date(new Date()-7*60*60*24*1000)]}
]
}
}}, {$group: {
_id: '$userId',
totalSeen: {
$sum: {
$cond: [
{
$eq: [
'$status',
'seen'
]
},
1,
0
]
}
},
total: {
$sum: 1
}
}}, {$project: {
_id: 0,
userId: '$_id',
notificationPercentage: {
$multiply: [
{
$divide: [
'$totalSeen',
'$total'
]
},
100
]
}
}}]
推荐阅读
- debugging - 通过 Dbeaver 客户端进行远程调试
- ios - 如何在编码失败时中止 iOS Alamofire Multipart Upload
- swift - 在 SpriteKit SKPhysicsContactDelegate 中未检测到联系人
- android - python - 按文件名打开类似文件的对象
- php - 为什么方法不能返回布尔值?
- javascript - 函数的意外未定义返回值
- c# - 传入字典的模型项是 Razor mvc5 中的“System.Collections.Generic.List”类型
- reactjs - 反应滑动导航
- javascript - 如何在 Leaflet openPopup 中设置各种选项?
- python - 如何从 keras API 模型中获取 tf.gradients?