问题
I am trying to fetch all the documents based on date filters as below in MongoDB:
- This Week only
- Last Week only
- This Month only
- Last Month only
- Between Custom Dates.
My collection:
[
{
_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"),
}]
Expected Result:
- When This_Week Filter is applied - fetch all the userIds whose createdAt falls in this week and then calculate the notification percentage.
[{
userId : "589",
notificationPercentage: 100% // Because userId 589 has 2 seen documents for this week.
}]
- When This_Month filter is applied: - userId 589 and userId 113 was created in this month and calculating the notificationPercentage for it.
[{
userId : "589",
notificationPercentage: 66.66%
},
{
userId : "113",
notificationPercentage: 0%
}]
- When Last_month filter is applied:
[{
userId : "112",
notificationPercentage: 50% //Because only userId 112 was created in last month and finding the notification percentage for it.
}]
- When Last_week filter is applied:
[{
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.
}]
Formula for notification percentage -
(No of times the user has seen/no of times he got notifications) * 100
回答1:
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
]
}
}}]
来源:https://stackoverflow.com/questions/64924624/how-to-get-the-documents-based-on-date-filtersweek-month-and-custom-dates-in