【问题标题】:Flatten Parent child collection using mongodb使用 mongodb 展平父子集合
【发布时间】:2019-07-31 16:49:43
【问题描述】:

我需要在 mongodb 中展平我的父子集合。这类似于在以下位置询问 sql 的问题:

Flatten parent child hierarchy with multiple parents

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

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

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

请帮忙

【问题讨论】:

    标签: mongodb mongoose mongoose-schema mongoose-populate


    【解决方案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

    希望对你有所帮助。

    【讨论】:

    • 非常感谢。多重查找和展开工作得很好。唯一的问题是输出。我做了一个小改动。实际上,第一次查找以 l3 结束,然后是 l2 ,最后是 l1 ......所以,项目; {..... } 标签需要颠倒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-17
    • 2012-03-26
    相关资源
    最近更新 更多