Mongodb嵌套树结构

时间:2018-08-24 09:16:53

标签: mongodb mongodb-query aggregation-framework aggregate

如何以树格式获取直接子数据?

考虑以下样本数据。...如果搜索键为印度,则结果应包含具有项目数据的所有子节点...

项目收藏

[ 
 { id : 1, name : "p1" location : Pune },
 { id : 2, name : "p2" location : Mumbai },
 { id : 3, name : "p3" location : Nashik },
 { id : 4, name : "p4" location : Pune },
 { id : 5, name : "p5" location : Maharashstra },
 { id : 6, name : "p6" location : Pune }
 ]

位置信息收集

 [
 {id : 1 name : 'l1' , 'location' : Pune , parentLocation : Maharashstra},
 {id : 2 name : 'l2' , 'location' : Nashik , parentLocation : Maharashstra},
 {id : 3 name : 'l3' , 'location' : Mumbai , parentLocation : Maharashstra},
 {id : 4 name : 'l4' , 'location' : Maharashstra , parentLocation : India},
 {id : 5 name : 'l5' , 'location' : India , parentLocation : null}

 ]

预期结果应该在下面。...使用mongo聚合

我想检索所有项目计数以及详细信息。...

预期产量

 India - p1,p2,p3,p4,p5
    Maharashstra - p5
       Pune - p1,p4
       Mumbai - p2
       Nashik - p3

预期的Json输出

{
"location": "India",
"parentLocation": null,
"Child": [
    {
        "location": "Maharashstra",
        "parentLocation": "India",
        "ProjectCount": 6,
        "ProjectDetails" : [
            { "id" : 5, "name" : "p5", "location" : "Maharashstra"
            }
        ],
        "Child": [
            {
                "location": "Pune",
                "parentLocation": "Maharashstra",
                "ProjectCount": 3,
                "ProjectDetails": [
                    {
                        "id": 1,
                        "name": "p1",
                        "location": "Pune"
                    },
                    {
                        "id": 4,
                        "name": "p4",
                        "location": "Pune"
                    },
                    {
                        "id": 6,
                        "name": "p6",
                        "location": "Pune"
                    }
                ]
            },
            {
                "location": "Nashik",
                "parentLocation": "Maharashstra",
                "ProjectCount": 1,
                "ProjectDetails": [
                    {
                    "id": 3,
                    "name": "p3",
                    "location": "Nashik"
                    }
                ]
            },
            {
                "location": "Mumbai",
                "parentLocation": "Maharashstra",
                "ProjectCount": 1,
                "ProjectDetails": [
                    {
                    "id": 2,
                    "name": "p2",
                    "location": "Mumbai"
                    }
                ]
            }
        ]
    }
]

}

请参考上面的树...以获取输出 谢谢...。

0 个答案:

没有答案