本文介绍了如何在MongoDB中基于日期过滤器(周,月和自定义日期)获取文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图根据日期过滤器来获取所有文档,如下所示:
I am trying to fetch all the documents based on date filters as below in 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下降的所有用户ID,然后计算通知百分比.
[{
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%
}]
- 应用上个月"过滤器:
[{
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.
}]
通知百分比的公式-(用户没有看到次数/没有收到通知的次数)* 100
推荐答案
您可能会有类似以下内容.使用匹配操作进行过滤.在此示例中,我向您显示了last_week的详细信息.我检查了您上面提到的所有方案.而且工作正常
You may have some thing like following. Use match operation to filter out. In this example I have shown you the last_week details. I checked all scenarios that you mentioned above. And its working fine
[{$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
]
}
}}]
这篇关于如何在MongoDB中基于日期过滤器(周,月和自定义日期)获取文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!