使用mongodb拼合父子集合

问题描述 投票:1回答:1

我需要在mongodb中展平我的父子集合。这类似于sql所要求的问题:

Flatten parent child hierarchy with multiple parents

我的集合类似于:{_ id,type,name,parent :(映射到self,即类别集合))}

当前儿童的深度为3,类型为L1,L2,L3

结果将包含以下字段:(L1_id,L1_name,L2_id,L2_name,L3_id,L3_name)

请帮助

mongodb mongoose mongoose-schema mongoose-populate
1个回答
1
投票

您可以使用mongodb aggregation pipeline来实现相同的目标。更具体地说,您可以使用$lookup两次填充parent及其parent,最后使用$project来压平结构。

试试这个:

Category.aggregation([{
    $lookup : {
        from :"categories",
        localField : "parent",
        foreignField : "_id",
        as  :"parent"
    }
},{
    $unwind : "$parent"
},{
    $lookup : {
        from :"categories",
        localField : "parent.parent",
        foreignField : "_id",
        as  :"parent.parent"
    }
},{
    $unwind : "$parent.parent"
},{
    $project : {
        l1_id  : "$_id",
        l1_name : "$name",
        l2_id : "$parent._id", 
        l2_name : "$parent.name" ,
        l3_id : "$parent.parent._id", 
        l2_name : "$parent.parent.name" 
    }
}]).then(result => {
    // result will have l1_id, l1_name, l2_id, l2_name, l3_id, l3_name
    // where l2 is the parent,
    // and l3 is the parent of parent 
}).

注意:在$unwind阶段之后使用$lookup,因为$lookup返回一个数组,我们需要将它展开以将其转换为对象。

欲了解更多信息,请阅读Mongodb $lookup documentation$project documentation

我希望这能够帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.