检索完整的树结构

时间:2018-08-01 17:14:31

标签: mongodb tree aggregation

我们在mongoDB中保留了类似树的结构。树的结构是动态的,深度的。类似于文件夹可能具有的结构。我们正在尝试使用聚合来检索完整的树结构,到目前为止还没有运气。

结构如何在mongoDB中持久化的示例:

[{
    _id: 1,
    name: "top-level",
    parent: null
},{
    _id: 2,
    name: "second-level-a",
    parent: 1 // top-level
},{
    _id: 3,
    name: "second-level-b",
    parent: 1 // top-level
},{
    _id: 4,
    name: "third-level",
    parent: 2 // second-level-a
}]

为获得与我们所寻找的结果最接近的结果,使用了以下内容:

db.pages.aggregate([
    {
        "$graphLookup": {
            "from": "pages",
            "startWith": "$_id",
            "connectFromField": "_id",
            "connectToField": "parent",
            "as": "subPages",
            "maxDepth": 1,
            "depthField": "depth"
        }
    }, {
        "$match": {
            "parent": null
        }
    }
])

我们得到的结果如下:

[
    {
        _id: 1,
        name: "first-level",
        parent: null,
        subPages: [
            {
                _id: 2,
                name: "second-level-a",
                depth: 0,
                [...]
            },{
                _id: 3,
                name: "second-level-b",
                depth: 0,
                [...]
            },{
                _id: 4,
                name: "third-level",
                depth: 1,
                [...]
            }

        ]
    }
]

期望的结果是这样

[
    {
        _id: 1,
        name: "first-level",
        parent: null,
        subPages: [
            {
                _id: 2,
                name: "second-level-a",
                depth: 0,
                [...]
                subPages: [
                    {
                        _id: 4,
                        name: "third-level",
                        depth: 1,
                        [...]
                    }
                ]
            },{
                _id: 3,
                name: "second-level-b",
                depth: 0,
                [...]
            }

        ]
    }
]

仅通过mongoDB的功能是否有可能达到我们之后的结果?

0 个答案:

没有答案