比较并在嵌套数组中添加两个数组 [英] Compare and add two array inside nested arrays

查看:227
本文介绍了比较并在嵌套数组中添加两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的文档中有下面的数组

I have below array of array inside my document

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

我需要将TaxTax组合在一起,并将FX AdjustmentsFX Adjustments组合在一起.

I need to combine Tax with Tax and FX Adjustments with FX Adjustments.

我需要的输出

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

我尝试过但没有运气

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

请为此提供帮助

谢谢!

推荐答案

您需要从 $ arrayElemAt ).然后,您可以像尝试过那样运行 $ red 由于数组是多维数组,因此需要使用 $ map进行包装代表索引.要恢复原始数据格式,可以按null分组并使用

You need to start with $unwind and then $group by first array element ($arrayElemAt). Then you can run $reduce like you tried but since your array is multidimensional, you need to wrap it with $map to represent the index. To get back the original data format you can group by null and use $concatArrays to put grouping _id as first array element:

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" ] } }
        }
    }
])

蒙戈游乐场

这篇关于比较并在嵌套数组中添加两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆