数字数组的求和

时间:2019-07-18 11:31:12

标签: node.js mongodb aggregation-framework

我想根据两个数组pbdinput找到一个总数。 每当类型和大小匹配时,流水线就应该将pbd.charge.sellRateinput.quantity相乘。另外,我也想将所有这些加在一起以获得总计。

输入应为

  {
    "pbd": [
      {
        "type": "STD",
        "size": "20",
        "charge": {
          "sellRate": 120
        }
      },
      {
        "containerType": "STD",
        "containerSize": "40",
        "charge": {
          "sellRate": 290
        }
      }
    ],
    "input": [
      {
        "type": "STD",
        "size": "20",
        "quantity": "20"
      },
      {
        "type": "STD",
        "size": "40",
        "quantity": "20"
      }
    ]
  }

到目前为止,我已经使用了两个$map运算符,就像两个for循环一样:

db.collection.aggregate([
  {
    $project: {
      "grandTotal": {
        $map: {
          input: "$pbd",
          as: "pbd",
          in: {
            $map: {
              input: "$input",
              as: "inp",
              in: {
                $cond: {
                  if: {
                    $and: [
                      {
                        $eq: [
                          "$$pbd.type",
                          "$$inp.type"
                        ]
                      },
                      {
                        $eq: [
                          "$$pbd.size",
                          "$$inp.size"
                        ]
                      }
                    ]
                  },
                  then: {
                    $multiply: [
                      {
                        $toInt: "$$pbd.charge.sellRate"
                      },
                      {
                        $toInt: "$$inp.quantity"
                      }
                    ]
                  },
                  else: 0
                }
              }
            }
          }
        }
      }
    }
  }
])

我得到的输出是这个

  {
    "_id": ObjectId("5a934e000102030405000000"),
    "grandTotal": [
      [
        2400,
        0
      ],
      [
        0,
        0
      ]
    ]
  }

现在,我想将所有这些数组数组相加以获得总计。对于此问题的更好解决方案也将受到高度赞赏。

这是一个很长的聚合管道的一部分,其中包含许多其他数据,因此我宁愿不要展开数据并将其分组。还有其他选择吗?

1 个答案:

答案 0 :(得分:1)

您可以在管道的下一步中运行$reduce

db.collection.aggregate([
    // your current aggregation pipeline
    {
        $project: {
            total: {
                $reduce: {
                    input: "$grandTotal",
                    initialValue: 0,
                    in: {
                        $add: [ "$$value", { $sum: "$$this" } ]
                    }
                }
            }
        }
    }
])

Mongo Playground