如何查询数据,并按月分组以提供折线图?

How to query data, and group them by month to feed line charts?

我遇到了一些问题,我不知道应该在 MongoDB 文档中搜索什么关键字。

所以问题是,我现在有一个用户的交易记录列表,例如如下。

[
    {
        "_id": Some_Mongo_ID,
        "invoiceId": "ABCDEFG",
        "username": "randomUser"
        "amount": 80,
        "createdAt": "2022-04-18T06:59:07.836Z"
    },
    {
        "_id": Some_Mongo_ID,
        "invoiceId": "ABCDEFG",
        "username": "randomUser"
        "amount": 70,
        "createdAt": "2022-04-19T06:59:07.836Z"
    },
    {
        "_id": Some_Mongo_ID,
        "invoiceId": "ABCDEFG",
        "username": "randomUser"
        "amount": 55,
        "createdAt": "2022-05-18T06:59:07.836Z"
    },
        ...
]

在我现在使用的仪表板应用程序中,有一个折线图。要提供折线图,我需要以某种方式 query/aggregation 我拥有的交易原始数据,并将它们分组到一个对象数组中,其中包含该月的月份和总支出。

[
    {
      "period": "2022-04",
      "totalSpending": 900
    },
    {
      "period": "2022-05",
      "totalSpending": 2000
    },
    {
      "period": "2022-06",
      "totalSpending": 367
    },
      ...
]

技术上是否可以 query/aggregate 我拥有的数据并将它们按月分组到一个数组中,如上所示?

如能提供任何信息,将不胜感激。谢谢

Playground

db.collection.aggregate([
  {
    "$group": {
      "_id": {
        month: { //Group by Month
          "$month": "$createdAt"
        },
        year: { //Group by Year
          "$year": "$createdAt"
        }
      },
      "totalSpending": { //Accumulate sum for the group
        $sum: "$amount"
      }
    }
  },
  {
    "$project": { //You can ignore this if the group format is ok
      "totalSpending": 1,
      "period": { //To form the expected string
        "$concat": [
          {
            $toString: "$_id.year"
          },
          "-",
          {
            $toString: "$_id.month"
          }
        ]
      },
      "_id": 0
    }
  }
])