Node.js 在嵌套数组中比较并添加两个数组
我的文档中有以下数组Node.js 在嵌套数组中比较并添加两个数组,node.js,mongodb,mongodb-query,aggregation-framework,Node.js,Mongodb,Mongodb Query,Aggregation Framework,我的文档中有以下数组 { items: [ ["Tax", 10, 20, 30], ["FX Adjustments", 10, 20, 30], ["Tax", 10, 20, 30], ["FX Adjustments", 10, 20, 30] ] } 我需要将税务与税务和外汇调整与外汇调整相结合 我需要的输出 { items: [ ["Tax", 20, 40, 60], ["
{
items: [
["Tax", 10, 20, 30],
["FX Adjustments", 10, 20, 30],
["Tax", 10, 20, 30],
["FX Adjustments", 10, 20, 30]
]
}
我需要将税务
与税务
和外汇调整
与外汇调整
相结合
我需要的输出
{
items: [
["Tax", 20, 40, 60],
["FX Adjustments", 20, 40, 60]
]
}
我试过了,但没有成功
db.collection.aggregate([
{
$project: {
items: {
$reduce: {
input: "$items",
initialValue: [],
in: {
$cond: [
]
}
}
}
}
}
])
请帮忙
谢谢你 试试下面的聚合管道
collectionName.aggregate([
{
$unwind: "$items"
},
{
$group: {
_id: {
$arrayElemAt: [
"$items",
0
]
},
sum1: {
$sum: {
$arrayElemAt: [
"$items",
1
]
}
},
sum2: {
$sum: {
$arrayElemAt: [
"$items",
2
]
}
},
sum3: {
$sum: {
$arrayElemAt: [
"$items",
3
]
}
}
}
},
{
$project: {
_id: null,
items: {
$map: {
input: {
$objectToArray: "$$ROOT"
},
as: "item",
in: "$$item.v"
}
}
}
},
{
$group: {
_id: null,
items: {
$push: "$items"
}
}
}
])
[
{
"_id": null,
"items": [
[
"Tax",
20,
40,
60
],
[
"FX Adjustments",
20,
40,
60
]
]
}
]
您需要从第一个数组元素()开始,然后是第一个数组元素()。然后,您可以像您尝试的那样运行,但是由于您的数组是多维的,因此需要使用包装来表示索引。要恢复原始数据格式,您可以按null
分组,并使用将分组\u 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" ] } }
}
}
])
如果有3个以上的数组元素怎么办?如果没有
$unwind
。。。使用$reduce
?@教授理论上是的,但代码在我看来是可读的-您可以尝试使用$let
和$arrayElemAt
谢谢您,但如果您可以这样告诉我。。。我很容易理解。。。顺便说一句,IMO是什么?依我看