使用mongodb展平父级子级集合

时间:2019-03-10 02:01:11

标签: mongodb mongoose mongoose-schema mongoose-populate

我需要在mongodb中展平我的父母孩子的收藏。这类似于在

处询问sql的问题

Flatten parent child hierarchy with multiple parents

我的收藏就像 类别:{_ id,类型,名称,父项:(映射到自身,即类别集合))}

L1,L2,L3类型的孩子当前的深度为3

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

请帮助

1 个答案:

答案 0 :(得分: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,因为width:100 height:100返回一个数组,我们需要将其展开以将其转换为对象。

有关更多信息,请阅读Mongodb $lookup documentation$project documentation

我希望这对您有所帮助。