问题

我想只使用MongoDB Aggregate完成一项任务,而不需要额外的代码.这与我们运行聚合的环境有关.

我们有users件藏品.在我们的应用程序中,可以创建和删除用户.createdAt字段具有创建用户的日期,而deletedAt字段具有删除用户的日期.

我想创建一个聚合,能够计算的活跃(不删除)不同的用户数量,我们每个月,从第一个用户被创建的月份,直到现在.

用更古怪的话来说,我想找出从创建第一个用户的月份开始,每个日期范围从createdAt开始到deletedAt结束的日期范围的数量,这些日期范围与每个月相交.我们希望避免手动输入每个月,因为这会 destruct 我们想要进行的自动化,所以我们需要以编程方式获取月份,这样聚合现在和将来都可以工作.

示例

让我们假设我的集合users具有以下三个条目:

{
    "_id" : ObjectId("5fbf2996846471279461asd87"),
    "createdAt" : ISODate("2023-07-26T04:05:36.314Z"),
    "deletedAt" : ISODate("2023-11-15T07:06:36.314Z"),
}, {
    "_id" : ObjectId("6fbf2996846471279461asd87"),
    "createdAt" : ISODate("2023-09-05T09:05:36.314Z"),
}, {
    "_id" : ObjectId("7fbf2996846471279461asd87"),
    "createdAt" : ISODate("2023-10-14T04:05:36.314Z"),
    "deletedAt" : ISODate("2023-10-15T07:06:36.314Z"),
},

所以我希望输出是这样的:

{
  "month": "2023-07",
  "count": 1,
}, {
  "month": "2023-08",
  "count": 1,
}, {
  "month": "2023-09",
  "count": 2,
}, {
  "month": "2023-10",
  "count": 3,
}, {
  "month": "2023-11",
  "count": 2,
}, {
  "month": "2023-12",
  "count": 1,
}, {
  "month": "2024-01",
  "count": 1,
},

如有任何帮助,我们不胜感激!

谢谢!

推荐答案

一种 Select 是使用日期运算符$range for each 文档创建月份日期列表:

db.collection.aggregate([
  {$project: {
      months: {
        $let: {
          vars: {
            startMonth: {$dateTrunc: {date: "$createdAt", unit: "month"}},
            endMonth: {$dateTrunc: {date: {$ifNull: ["$deletedAt", "$$NOW"]}, unit: "month"}}
          },
          in: {$map: {
              input: {$range: [
                  0,
                  {$add: [
                      {$dateDiff: {startDate: "$$startMonth", endDate: "$$endMonth", unit: "month"}},
                      1
                  ]}
              ]},
              in: {$dateToString: {
                  date: {$dateAdd: {
                      startDate: "$$startMonth", unit: "month", amount: "$$this"
                  }},
                  format: "%Y-%m"
              }}
            }
          }
        }
      }
  }},
  {$unwind: "$months"},
  {$group: {_id: "$months", count: {$sum: 1}}},
  {$sort: {_id: 1}},
  {$project: {createdAt: "$_id", count: 1, _id: 0}}
])

看看它在playground example号公路上是如何工作的

Mongodb相关问答推荐

匹配/筛选/投影对象中数组中数组中的嵌套字段

MongoDB 投影按数组中的字符串长度排序

如何在MongoDB中搜索有序子集的方法?

分组前的 MongoDb 聚合总数

Mongo:查找具有 0 个关联文档的文档,成本更低

在 MongoDB 中加入多个集合

在运算符 $map 中嵌入运算符 $exists

没有mongoose 的 Express 和 MongoDB

如何将 json 字符串编组到 bson 文档以写入 MongoDB?

Mongoexport 在日期范围内使用 $gt 和 $lt 约束

我怎样才能排序空值在 mongodb 中是最后排序的?

MongoDB插入引发重复键错误

在mongodb中实现分页

为 php 5.6 (XAMPP) 添加 mongodb 扩展

MongoDB展开多个数组

嵌套数组内的Mongodb增量值

使用 Java 驱动程序更新 MongoDB 中的数组

如何在 Meteor 应用程序之间共享 MongoDB 集合?

MongoError:failed to connect to server [localhost:27017] on first connect

我可以使用字符串作为 mongodb 文档的 ID 类型吗?