HawkLu92
HawkLu92
  • 发布:2021-11-15 11:05
  • 更新:2021-11-15 14:24
  • 阅读:333

求一个聚合查询

分类:uniCloud

求一个聚合查询的方法,自己折腾了好久都没折腾出来。。提前谢谢
有一个商品分类表,用于存放一级于二级分类,一级类目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"  
            }  
        ]  
    }  
]  
2021-11-15 11:05 负责人:无 分享
已邀请:
DCloud_uniCloud_WYQ

DCloud_uniCloud_WYQ

lookup+pipeline副表也写这个表就行

  • HawkLu92 (作者)

    好的,谢谢,已搞定

    2021-11-15 14:23

HawkLu92

HawkLu92 (作者) - GoodGoodCoding,DayDayNoBug

已搞定:

const db = uniCloud.database();   
const dbCmd = db.command  
const $ = db.command.aggregate  
exports.main = async (event, context) => {  
    let res = await db.collection('opendb-mall-categories').aggregate()  
        .match({  
            parent_id:""  
        })  
        .lookup({  
            from:"opendb-mall-categories",  
            let:{  
                parent_id:"$_id",  
            },  
            pipeline:$.pipeline()  
                .match(dbCmd.expr($.eq(['$parent_id', '$$parent_id'])))  
                .done(),  
            as:"children"  
        })  
        .end()  
    return res;  
};  
  • HawkLu92 (作者)

    先match获取parent_id为空的一级类目,传递下去,用lookup联查当前表中parent_id为一级_id的数据,用到了let声明了个变量

    2021-11-15 14:27

该问题目前已经被锁定, 无法添加新回复