比较并在嵌套数组中添加两个数组 [英] Compare and add two array inside nested arrays
本文介绍了比较并在嵌套数组中添加两个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的文档中有下面的数组
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]
]
}
我需要将Tax
与Tax
组合在一起,并将FX Adjustments
与FX 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: [
]
}
}
}
}
}
])
请为此提供帮助
谢谢!
推荐答案
您需要从 $ group 按第一个数组元素( $ 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屋!
查看全文