MongoDB中嵌套数组的$ reduce和$ setUnion [英] $reduce and $setUnion for nested arrays in MongoDB
问题描述
我正在MongoDB中使用$ reduce和$ setUnion合并嵌套数组.以下是示例输入-
I am looking to merge nested arrays using $reduce and $setUnion in MongoDB. Following is the sample input -
levels: [
[[80,100,120]],[[100,150]],[[200,80,100]],[[80,100]]
]
我打算得到的输出(即,将嵌套数组与唯一值合并)- 级别:[80,100,120,150,100]
The output what I am intended to get (i.e. merge nested arrays with unique values) - levels: [80,100,120,150,100]
我可以通过两种方法获得上述输出-
I am able to get the above output using two ways -
1)在管道中使用两个$ project阶段-
1) Using two $project stages in pipeline -
aggregate([
$project: { levels : { $reduce: {
input: "$levels", initialValue: [], in:{$setUnion:["$$value","$$this"]}}}},
$project: { levels : { $reduce: {
input: "$levels", initialValue: [], in:{$setUnion:["$$value","$$this"]}}}}
])
2)首先$ unwind,然后$ project
2) First $unwind and then $project
aggregate([
$unwind: { '$levels'}},
$project: { levels : { $reduce: {
input: "$levels", initialValue: [], in:{$setUnion:["$$value","$$this"]}}}}
])
在我不需要两次使用相同的$ project的情况下,有没有一种改进的第一选择方式?我正在努力避免放松.
Can there be any improved way of first option where I don't need to use the same $project twice? I am trying to avoid unwind.
推荐答案
您可以将以下聚合与单个 $project
阶段
You can use below aggregation with single $project
stage
db.collection.aggregate([
{ "$project": {
"levels": {
"$reduce": {
"input": {
"$reduce": {
"input": "$levels",
"initialValue": [],
"in": { "$setUnion": ["$$this", "$$value"] }
}
},
"initialValue": [],
"in": { "$setUnion": ["$$this", "$$value"] }
}
}
}}
])
这篇关于MongoDB中嵌套数组的$ reduce和$ setUnion的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!