MongoDB树结构

时间:2017-03-04 20:33:03

标签: json mongodb tree parent-child

我有一个带有以下文件的Mongo集合:

{
    "_id" : ObjectId("58b09a97f630f3070ad0cabd"),
    "Parent" : "",
    "ID" : "123"
},

{
    "_id" : ObjectId("58b09a97f630f3070ad0cabe"),
    "Parent" : "123",
    "ID" : "098"
},

{
    "_id" : ObjectId("58b09a97f630f3070ad0caca"),
    "Parent" : "123",
    "ID" : "567"
},

{
    "_id" : ObjectId("58b09a97f630f3070ad0cabf"),
    "Parent" : "098",
    "ID" : "abc"
},

{
    "_id" : ObjectId("58b09a97f630f3070ad0cace"),
    "Parent" : "567",
    "ID" : "def"
}

我想创建一个格式为

的集合
{
    "ID" : 123,
    "children" : [ 
        {
            "ID" : "098",
            "childs" : [ 
                {
                    "ID" : "abc",
                }
            ]
        }, 
        {
            "ID" : 567,
            "childs" : [ 
                {
                    "ID" : "def"
                }
             ]
         }
     ]
}

我能够执行正确的查询以查找每个父级的所有子级,但无法找到将文档导出为上面列出的树格式的新集合的方法。感谢所有帮助!

0 个答案:

没有答案