MongoDB/TypeScript中提取父子结构文档的所有层级子节点数组值至单个数组
MongoDB/TypeScript中提取父子结构文档的所有层级子节点数组值至单个数组
我来帮你搞定这个提取所有层级子节点数组的需求,不管是用MongoDB原生聚合查询,还是拿到数据后用TypeScript处理,都有靠谱的方案,咱们一个个来看:
一、MongoDB聚合查询方案
如果想直接在数据库层面完成这个操作,用$graphLookup递归查询所有后代节点,再把所有层级的childrenGroupList合并成一个数组就可以了。具体的聚合管道如下:
db.collection.aggregate([ // 第一步:匹配到目标根节点(itemGroupName为"PARI"的文档) { $match: { itemGroupName: "PARI" } }, // 第二步:递归查询所有后代节点,建立层级关系 { $graphLookup: { from: "collection", // 替换成你的集合名称 startWith: "$childrenGroupList", connectFromField: "childrenGroupList", connectToField: "itemGroupName", as: "allDescendants", maxDepth: -1 // 不限制递归深度,获取所有层级后代 } }, // 第三步:把根节点的childrenGroupList和所有后代的childrenGroupList收集到一起 { $project: { allChildren: { $concatArrays: [ "$childrenGroupList", { $reduce: { input: "$allDescendants", initialValue: [], in: { $concatArrays: ["$$value", "$$this.childrenGroupList"] } } } ] } } }, // 第四步:只输出合并后的数组(可选,根据需求调整) { $project: { _id: 0, allChildren: 1 } } ])
这个管道的逻辑是:先找到根节点,再递归拉取所有后代,接着用$reduce把所有后代的childrenGroupList合并成一个数组,最后和根节点的childrenGroupList拼接起来,得到最终的全层级子节点数组。
二、TypeScript处理方案
如果已经把所有文档获取到了内存中(比如通过MongoDB驱动查询到数组),可以写一个递归函数来遍历所有层级,收集目标值。示例代码如下:
// 定义文档的类型 interface ItemGroup { itemGroupName: string; childrenGroupList: string[]; // 其他字段可以按需添加 } // 假设这是从数据库拿到的所有文档数组 const allGroups: ItemGroup[] = [ // 这里放你的示例文档数据 ]; // 递归收集所有层级的childrenGroupList元素 function collectAllChildren(rootName: string): string[] { // 先找到当前节点 const currentGroup = allGroups.find(g => g.itemGroupName === rootName); if (!currentGroup) return []; // 收集当前节点的子节点,再递归收集每个子节点的子节点 const children = [...currentGroup.childrenGroupList]; currentGroup.childrenGroupList.forEach(childName => { children.push(...collectAllChildren(childName)); }); return children; } // 使用示例:提取"PARI"的所有层级子节点 const result = collectAllChildren("PARI"); console.log(result); // 输出:["DREAMS PARI", "DREAMS PARI 001", "DREAMS PARI 002", "DREAMS PARI 002B"]
这个函数的逻辑是:先找到指定名称的节点,把它的子节点加入结果数组,然后对每个子节点递归执行同样的操作,把递归返回的子节点数组也合并进来,最终得到所有层级的子节点集合。
备注:内容来源于stack exchange,提问作者user11586200
相关产品推荐
相关产品推荐

