在 MongoDB 中简化 graphLookup 输出

Simplifying graphLookup output in MongoDB

我有一个形式为“people”的集合:

{ "_id" : 1, "name" : "Grandma"}   
{ "_id" : 2, "name" : "Mum", "parentID": "1"}  
{ "_id" : 3, "name" : "Uncle", "parentID": "1"}  
{ "_id" : 4, "name" : "Kid", "parentID": "2"}  
{ "_id" : 5, "name" : "Sister", "parentID": "2"}

要获取某个人(比如 Kid)的祖先,我可以使用简单的匹配和 graphLookup,如下所示:

people.aggregate([  
    {$match: {_id: "3"}},  
    {$graphLookup:  
        {  
        from: "people",  
        startWith: "$parentID",  
        connectFromField: "parentID",  
        connectToField: "_id",  
        as: "ancestors"  
        }  
    }  
])

这将 return

{ "_id" : 3, "name" : "Kid", "parentID": "2", "ancestors": [
    { "_id" : 1, "name" : "Grandma"},
    { "_id" : 2, "name" : "Mum", "parentID": "1"}]
}

我卡住的地方是如何将此输出数据重构为单个分层数组,这样:

array = [  
{ "_id" : 1, "name" : "Grandma"},    
{ "_id" : 2, "name" : "Mum", "parentID": "1"},  
{ "_id" : 3, "name" : "Kid", "parentID": "2"}  
]

(数组顺序不重要)。

如有任何帮助,我们将不胜感激!

  • 只需要将 startWith frmo parentID 更改为 _id,这将 return ancestors 与当前文档
  • $project 显示必填字段
result = people.aggregate([
  { $match: { _id: "3" } },
  {
    $graphLookup: {
      from: "collection",
      startWith: "$_id",
      connectFromField: "parentID",
      connectToField: "_id",
      as: "ancestors"
    }
  },
  {
    $project: {
      _id: 0,
      ancestors: 1
    }
  }
])

Playground

通过以下方式访问数组:

finalResult = result[0]['ancestors']