如何计算两个具有相同键但不同字段的对象数组的总值,并在 MongoDB 中使用聚合将它们合并为一个?

问题描述 投票:0回答:1

我以数组形式返回数据,如下所示:

[{
    "_id" : ObjectId("65aa4921c767f95a70b8867f"),
    "creator" : "Henry",
    "date" : "2023-12-22",
    "channels" : [
        {
            "key" : "HTV",
            "value" : 1
        }
    ]
},
{
    "_id" : ObjectId("65aa4921c767f95a70b8867f"),
    "creator" : "Max",
    "date" : "2023-12-23",
    "channels" : [
        {
            "key" : "VTC",
            "value" : 1
        }
    ]
},
{
    "_id" : ObjectId("65aa4921c767f95a70b88689"),
    "creator" : "John",
    "date" : "2023-12-23",
    "channels" : [
        {
            "key" : "VTC",
            "value" : 2
        },
        {
            "key" : "HTV",
            "value" : 1
        }
    ]
}]

我想按日期分组,并且“channels”数组中具有相同键的元素将合并为一个 (具有相同键的通道的总值以及通道所有值的总和)

我使用聚合对“日期”进行分组:

model.aggregate([
      {
        $group: {
          _id: {
            date: '$date'
          },
          Total: { $sum: { $sum: '$channels.value' } }
        }
      }
    ])

但不知道下一步该怎么做(将重复的键合并为一个,并计算值的总和)

我的预期结果:

[{
    "date": "2023-12-22",
    "channels" : [
        {
            "key" : "HTV",
            "value" : 1
        }
    ],
    "Total" : 1
},
{
    "date": "2023-12-23",
    "channels" : [
        {
            "key" : "VTC",
            "value" : 3   // 1 + 2
        },
        {
            "key" : "HTV",
            "value" : 1
        }
    ],
    "Total" : 4
}]

谁能帮我解决这个问题吗?非常感谢各位的回复

mongodb mongoose aggregate group
1个回答
0
投票

也许你应该尝试展开数组字段并执行求和运算。

© www.soinside.com 2019 - 2024. All rights reserved.