求一个聚合查询的方法,自己折腾了好久都没折腾出来。。提前谢谢
有一个商品分类表,用于存放一级于二级分类,一级类目parent_id为空,数据如下:
{
"_id":"18ed09686190fe91052e14331649a71a",
"name":"一级类目1",
"parent_id":""
},
{
"_id":"fa24ce1a61910815066eec09203fa9b2",
"name":"二级类目1-1",
"parent_id":"18ed09686190fe91052e14331649a71a"
},
{
"_id":"fa24ce1a619108b2066f33a76a95da05",
"name":"二级类目1-2",
"parent_id":"18ed09686190fe91052e14331649a71a"
},
{
"_id":"18ed09686190fe91052e14331649a71b",
"name":"二级类目1",
"parent_id":""
},
{
"_id":"fa24ce1a61910815066eec09203fa9b3",
"name":"二级类目2-1",
"parent_id":"18ed09686190fe91052e14331649a71b"
},
{
"_id":"fa24ce1a619108b2066f33a76a95da06",
"name":"二级类目2-2",
"parent_id":"18ed09686190fe91052e14331649a71b"
}
如何查询输出成如下格式:
[
{
"_id":"18ed09686190fe91052e14331649a71a",
"name":"一级类目1",
"parent_id":"",
"children":[
{
"_id":"fa24ce1a61910815066eec09203fa9b2",
"name":"二级类目1-1",
"parent_id":"18ed09686190fe91052e14331649a71a"
},
{
"_id":"fa24ce1a61910815066eec09203fa9b2",
"name":"二级类目1-2",
"parent_id":"18ed09686190fe91052e14331649a71a"
}
]
},
{
"_id":"18ed09686190fe91052e14331649a71b",
"name":"一级类目2",
"parent_id":"",
"children":[
{
"_id":"fa24ce1a61910815066eec09203fa9b2",
"name":"二级类目2-1",
"parent_id":"18ed09686190fe91052e14331649a71a"
},
{
"_id":"fa24ce1a61910815066eec09203fa9b2",
"name":"二级类目2-2",
"parent_id":"18ed09686190fe91052e14331649a71a"
}
]
}
]
HawkLu92 (作者)
好的,谢谢,已搞定
2021-11-15 14:23