首页 > 解决方案 > 如何在 MongoDB 中获取基于日期过滤器(周、月和自定义日期)的文档?

问题描述

我正在尝试根据 MongoDB 中的以下日期过滤器获取所有文档:

  1. 仅限本周
  2. 仅限上周
  3. 仅限本月
  4. 仅上个月
  5. 自定义日期之间。

我的收藏:

[
  {
    _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"),
  }]

预期结果:

  1. 应用 This_Week 过滤器时 - 获取 createdAt 属于本周的所有 userId,然后计算通知百分比。
  [{
    userId : "589",
    notificationPercentage: 100% // Because userId 589 has 2 seen documents for this week.
  }]
  1. 应用 This_Month 过滤器时: - 本月创建了 userId 589 和 userId 113 并为其计算 notificationPercentage。
[{
  userId : "589",
  notificationPercentage: 66.66% 
},
{
  userId : "113",
  notificationPercentage: 0% 
}]
  1. 应用 Last_month 过滤器时:
[{
  userId : "112",
  notificationPercentage: 50% //Because only userId 112 was created in last month and finding the notification percentage for it.
}]
  1. 应用 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

标签: node.jsmongodbmongooseaggregation-framework

解决方案


您可能有类似以下的内容。使用匹配操作过滤掉。在此示例中,我向您展示了 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
    ]
  }
}}]

推荐阅读