首页 > 解决方案 > 数字数组数组的总和

问题描述

我想根据两个数组pbdinput. 只要类型和大小匹配,管道就应该将pbd.charge.sellRate与相乘。input.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
      ]
    ]
  }

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

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

标签: node.jsmongodbaggregation-framework

解决方案


您可以运行$reduce作为管道中的下一步:

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

蒙戈游乐场


推荐阅读