抱歉,我没有很好地理解MongoDB聚合。如何使用聚合实现以下功能:
[
{array: [1,2,3] },
{array: [4,5,6] },
{array: [7,8,9] }
]
desired result:
[1,2,3,4,5,6,7,8,9]
如果我将MongoDB聚合替换为将文档视为普通对象,性能会有所改变吗?
抱歉,我没有很好地理解MongoDB聚合。如何使用聚合实现以下功能:
[
{array: [1,2,3] },
{array: [4,5,6] },
{array: [7,8,9] }
]
desired result:
[1,2,3,4,5,6,7,8,9]
如果我将MongoDB聚合替换为将文档视为普通对象,性能会有所改变吗?
聚合总是比使用某些语言代码更好,因此数据库提供了这种类型的便利,以一次性获取结果。
原始答案翻译成“最初的回答”。
db.collection.aggregate([
{ "$group": {
"_id": null,
"data": { "$push": "$array" }
}},
{ "$project": {
"_id": 0,
"data": {
"$reduce": {
"input": "$data",
"initialValue": [],
"in": { "$concatArrays": ["$$this", "$$value"] }
}
}
}}
])
null
对$group进行分组,以获取数组的数组作为单个文档,然后你可以使用$concatArrays运行$reduce来展开该数组:db.col.aggregate([
{
$group: {
_id: null,
array: { $push: "$array" }
}
},
{
$project: {
_id: 0,
array: {
$reduce: {
input: "$array",
initialValue: [],
in: { $concatArrays: [ "$$value", "$$this" ] }
}
}
}
}
])
的英译中文为:{{链接1:MongoDB Playground}}
。