【问题标题】:Traversing through tree structure using mongoDB使用 mongoDB 遍历树结构
【发布时间】:2018-08-28 04:23:43
【问题描述】:

我是 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: []
}

【问题讨论】:

标签: mongodb tree aggregation-framework


【解决方案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,
    }
}])

【讨论】:

  • 你好@dnickless,感谢您的及时回复。我需要查询一个 id 并获得所需的输出以及父母和孩子的列表。
  • 非常感谢@dnickless。它帮助了我。当然,我正在做一些修改。我接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-28
相关资源
最近更新 更多