MongoDB 聚合 - 嵌套对象数组的总和

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

我正在使用 mongo:latest Docker 镜像(版本 mongo:7.0.7-jammy 截至目前)

我正在计算嵌套对象数组的总和,如下所示:

[
    {
        specificAmount: {
            amount: 200,
        }
    },
    {
        specificAmount: {
            amount: 300,
        }
    },
    ...
]

我要做这件事的方式是:

xxx.aggregate([
    {
      $group: {
        _id: null,
        count: { $sum: 1 },
        totalSpecificAmount: { $sum: '$specificAmount.amount' || 0 },
      },
    },
 ]).toArray())

计数工作正常,但totalSpecificAmount 的计算却不然——它总是返回

我该如何解决这个问题?

mongodb nosql
1个回答
0
投票

首先 - 感谢 @ray 的提示 $ifNull

这里的问题是 specificAmount.amount 不是我在问题中指定的数字 - 它们是字符串,无法求和。

xxx.aggregate([
    {
      $group: {
        _id: null,
        count: { $sum: 1 },
        totalSpecificAmount: { 
            $sum: { $ifNull: [{ $toInt: '$specificAmount.amount' }, 0]},
        },
      },
    },
 ]).toArray())
© www.soinside.com 2019 - 2024. All rights reserved.