使用mongoDB遍历树结构

时间:2018-08-27 19:37:49

标签: mongodb tree aggregation-framework

我是mongodb的新手,正在尝试聚合。我需要以下问题的帮助。 我有这样的收藏

{_id: 1,  parentId: null, name: 'foo'},
{_id: 2,  parentId: '1', name: 'boo'},
{_id: 3,  parentId: '2', name: 'koo'},
{_id: 4,  parentId: '3', name: 'coo'}
{_id: 5,  parentId: '4', name: 'loo'}

我想进行汇总并获取ID的父母和子女的列表。我该如何实现?预先感谢。

我尝试了mongodb的graphLookup,但未获得预期的结果。我试过了

    db.files.aggregate([ { $graphLookup: {
     from : 'files',
     startWith: '$id',
     connectFromField: 'parentId',
     connectToField: 'id',
     as: 'parents'
}}])

我需要的输出格式是:

{
id: id,
parents: [{id, name}],
children: []
}

1 个答案:

答案 0 :(得分:1)

parentId字段也更改为整数后,为了匹配_id字段,您可以执行以下操作:

db.files.aggregate([{
    $graphLookup: {
        from : 'files',
        startWith: '$parentId',
        connectFromField: 'parentId',
        connectToField: '_id',
        as: 'parents'
    }
}, {
    $graphLookup: {
        from : 'files',
        startWith: '$_id',
        connectFromField: '_id',
        connectToField: 'parentId',
        as: 'children'
    }
}])

根据您的评论,您似乎想在开始时添加一个$match阶段来查询特定的_id,并在末尾添加一个$project阶段来修剪输出到所需内容:

db.files.aggregate([{
    $match: {
        _id: 3
    }
}, {
    $graphLookup: {
        from : 'files',
        startWith: '$parentId',
        connectFromField: 'parentId',
        connectToField: '_id',
        as: 'parents'
    }
}, {
    $graphLookup: {
        from : 'files',
        startWith: '$_id',
        connectFromField: '_id',
        connectToField: 'parentId',
        as: 'children'
    }
}, {
    $project: {
        "parents._id": 1,
        "parents.name": 1,
        "children": 1,
    }
}])
相关问题