比较并在嵌套数组中添加两个数组

生产

我的文档中有下面的数组数组

  {
    items: [
      ["Tax", 10, 20, 30],
      ["FX Adjustments", 10, 20, 30],
      ["Tax", 10, 20, 30],
      ["FX Adjustments", 10, 20, 30]
    ]
  }

我需要TaxTaxFX Adjustments结合FX Adjustments

我需要的输出

  {
    items: [
      ["Tax", 20, 40, 60],
      ["FX Adjustments", 20, 40, 60]
    ]
  }

我尝试过但没有运气

db.collection.aggregate([
  {
    $project: {
      items: {
        $reduce: {
          input: "$items",
          initialValue: [],
          in: {
            $cond: [
            ]
          }
        }
      }
    }
  }
])

请对此提供帮助

谢谢!!!

米克尔

您需要以$ unwind开始,然后是$ group by第一个数组元素($ arrayElemAt)。然后,您可以像尝试过那样运行$ reduce,但是由于数组是多维的,因此需要用$ map包裹它来表示索引。要恢复原始数据格式,可以按分组null并使用$ concatArrays将分组_id作为第一个数组元素:

db.collection.aggregate([
    {
        $unwind: "$items"
    },
    {
        $group: {
            _id: { $arrayElemAt: [ "$items", 0 ] },
            values: { $push: { $slice: [ "$items", 1, { $size: "$items" } ] } }
        }
    },
    {
        $project: {
            _id: 1,
            values: {
                $map: {
                    input: { $range: [ 0, { $size: { $arrayElemAt: [ "$values", 0 ] } } ] },
                    as: "index",
                    in: {
                        $reduce: {
                            input: "$values",
                            initialValue: 0,
                            in: { $add: [ "$$value", { $arrayElemAt: [ "$$this", "$$index" ] } ] }
                        }
                    }
                }
            }
        }
    },
    {
        $group: {
            _id: null,
            items: { $push: { $concatArrays: [ [ "$_id" ], "$values" ] } }
        }
    }
])

蒙哥运动场

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章