MongoDB是否支持递归分组生成树形层级结构?
MongoDB 嵌套树形结构聚合查询解决方案咨询
现有数据库结构
数据文档结构如下:
{ "_id": { "code": "E1F417C68D71", "names": [ { "idx": 0, "type": "Level 0 name" }, { "idx": 1, "type": "Level 1 name" }, { "idx": 2, "type": "..." }, // 更多层级... ] }, "duplicatesCount": 1 // 示例整数 }, { "_id": { "code": "E1F238D90A06", "names": [ { "idx": 0, "type": "Level 0 other name" }, { "idx": 1, "type": "Level 1 name" }, { "idx": 2, "type": "..." }, // 更多层级... ] }, "duplicatesCount": 2 // 示例整数 }
期望输出树形结构
需要将数据转换为如下嵌套树形结构:
[{ "type": "Level 0 name", "duplicatesCount": 1, "childs": [{ "type": "Level 1 name", "duplicatesCount": 1, "childs": [ // 逐层嵌套至最后一级 { "type": "Level end name", "duplicatesCount": 1, "code": "E1F417C68D71", "childs": [] } ] }] }, { "type": "Level 0 other name", "duplicatesCount": 2, "childs": [{ ... }] }]
已尝试的聚合查询
目前尝试过按idx=0分组的聚合操作,但无法实现递归嵌套:
db.data.aggregate([ { "$group": { "_id" : { "name_idx_0": { "$first": "$_id.names" } }, "duplicatesCount": { "$sum": 1 }, "codes": { "$push": "$_id.code" } } }, ], { allowDiskUse: true });
疑问与需求
不确定该需求是否可通过MongoDB原生聚合实现。若通过循环逐层分组又担心效率过低,特此咨询可行的解决方案。
内容的提问来源于stack exchange,提问作者Polikarpos Goldshtein
相关产品推荐
相关产品推荐

