如何进行查询,包括集合的计数和数据

How to make a query includes both count and data of collection

示例数据

[
   { owner: '0x123124124', createdAt: '13 May 2022 at 04:20:21 UTC'},
   { owner: '0x123124124', createdAt: '13 May 2022 at 06:20:21 UTC'},
   { owner: '0x123124124', createdAt: '13 May 2022 at 03:20:21 UTC'},
   { owner: '0x123124124', createdAt: '12 May 2022 at 07:39:34 UTC'},
   { owner: '0x123124124', createdAt: '12 May 2022 at 07:39:34 UTC'},
   { owner: '0x454545627', createdAt: '11 May 2022 at 04:13:48 UTC'}
]

我想查询 return 这样的数据

[
  { owner: '0x123124124', createdAt: '13 May 2022', count: 3},
  { owner: '0x123124124', createdAt: '13 May 2022', count: 2},
  { owner: '0x454545627', createdAt: '11 May 2022', count: 1},
]

我已经研究了好几个小时了。 感谢您的帮助。

  1. $set - 将 createdAt 设置为

    1.1。 $trim - Trim 来自 1.1.1.

    的字符串

    1.1.1。 $arrayElemAt - 从 1.1.1.1.

    获取第一个值

    1.1.1.1。 $split - 用单词“at”拆分 createdAt 字符串。

  2. $group - 按 ownercreatedAt 分组并执行计数。

  3. $project - 修饰输出文档。

db.collection.aggregate([
  {
    $set: {
      createdAt: {
        $trim: {
          input: {
            "$arrayElemAt": [
              {
                $split: [
                  "$createdAt",
                  "at"
                ]
              },
              0
            ]
          }
        }
      }
    }
  },
  {
    $group: {
      _id: {
        owner: "$owner",
        createdAt: "$createdAt"
      },
      count: {
        $sum: 1
      }
    }
  },
  {
    $project: {
      _id: 0,
      owner: "$_id.owner",
      createdAt: "$_id.createdAt",
      count: 1
    }
  }
])

Sample Mongo Playground