MongoDB使用子引用数据生成树结构

时间:2017-08-25 04:27:18

标签: json mongodb tree

我想从子参考数据中获取树结构,如下所示:

{
"_id" : ObjectId("599f6e99a428843c34977669"),
"PI" : "A1",
"CI" : [
    "B1",
    "B2"
]},{
"_id" : ObjectId("599f6e99a428843c3497766a"),
"PI" : "B2",
"CI" : [
    "C1",
    "C2"
]},{
"_id" : ObjectId("599f6e99a428843c3497766b"),
"PI" : "A2",
"CI" : [
    "B3",
    "B4"
]},{
"_id" : ObjectId("599f6e99a428843c3497766c"),
"PI" : "B4",
"CI" : [
    "C1",
    "C3"
]},{
"_id" : ObjectId("599f7216a428843c3497766d"),
"PI" : "C1",
"CI" : [
    "D1",
    "D2"
]}

我参考指南https://www.codementor.io/slavko/storing-tree-structures-in-mongodb-example-code-du107tk8d 但仍然没有解决我的问题。

如何获得树结构:

{
"_id" : ObjectId("599f6e99a428843c34977669"),
"PI" : "A1",
"CI" : [
        "B1",
        {
        "PI" : "B2",
        "CI" : [
                {
                "PI" : "C1",
                "CI" : [
                        "D1",
                        "D2"
                        ]
                },
                "C2"
                ]
        }
        ]},{
"_id" : ObjectId("599f6e99a428843c3497766b"),
"PI" : "A2",
"CI" : [
        "B3",
        {
        "PI" : "B4",
        "CI" : [
                {
                "PI" : "C1",
                "CI" : [
                        "D1",
                        "D2"
                        ]
                },
                "C3"
                ]
        }
        ]}

此外,我希望我能通过具体的CI获得TOP祖先。

例如:

D1 - > A2,A1

C3 - > A2

0 个答案:

没有答案