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

埃卢先生

我遇到了一些问题,我不知道应该在 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"
    },
        ...
]

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

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

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

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

吉布斯

操场

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
    }
  }
])

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章