![](/img/trans.png)
[英]aggregation in nodejs resulting in nested json, can I get it without nesting, taking only one data _id from all collections
[英]How to get all _id from the nested JSON file using aggregation pipeline?
我的聚合管道中有以下结构数组。 尝试合并对象和 setUnion 运算符。
{
"_id": "6085232dd933b53b80a3de0c",
"parent": "6082b81ea6036499a33d0972",
"childNodes": [
{
"_id": "6084f8376d422a5baf527b6c",
"childNodes": [
{
"_id": "6084f9ab6d422a5baf527b6d",
"childNodes": [
{
"_id": "6084fa356d422a5baf527b6f",
"childNodes": [
{
"_id": "6084faa06d422a5baf527b70"
}
]
}
]
},
{
"_id": "6084f9ab6d422a5baf527b6d",
"childNodes": [
{
"_id": "6084fa356d422a5baf527b6f",
"childNodes": [
{
"_id": "6084faa06d422a5baf527b70"
}
]
}
]
}
]
}
]
}
我期待以下结果产生一些统计数据。
{
"allNodes":[allChildNodes-_ids]
}
您正在询问文档树的递归遍历。 这不是 mongo 擅长的。 从技术上讲,您可以在 javascript 中使用$function来执行:
.aggregate([
{
"$project": {
_id: 0,
"allNodes": {
$function: {
body: function(doc){
allIds = function(d) {
return [d._id].concat(...((d.childNodes || []).map(allIds)))
}
return allIds(doc)},
args: [
"$$ROOT"
],
lang: "js"
}
}
}
}
])
但性能会受到影响。 尾调用也没有优化,所以要小心深度嵌套的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.