MongoDB $ graphLookup-是否可以在嵌套文档中获取结果?

时间:2019-07-01 16:20:37

标签: mongodb graphlookup

我有一个树形结构,其中每个文档都指向其子级。

然后,我想在某个节点上执行$ graphLookup,并使节点降N级……但是,我不想获取列表或数组中的结果,而是想要获取嵌套的文档。

有可能这样做吗?

已编辑:

作为一个例子,让我们以documentation为例:

托收员工有以下文件:

{ "_id" : 1, "name" : "Dev" }
{ "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" }
{ "_id" : 3, "name" : "Ron", "reportsTo" : "Eliot" }
{ "_id" : 4, "name" : "Andrew", "reportsTo" : "Eliot" }
{ "_id" : 5, "name" : "Asya", "reportsTo" : "Ron" }
{ "_id" : 6, "name" : "Dan", "reportsTo" : "Andrew" }

执行的操作是:

db.employees.aggregate( [
   {
      $graphLookup: {
         from: "employees",
         startWith: "$reportsTo",
         connectFromField: "reportsTo",
         connectToField: "name",
         as: "reportingHierarchy"
      }
   }
] )

结果是:

{
   "_id" : 1,
   "name" : "Dev",
   "reportingHierarchy" : [ ]
}
{
   "_id" : 2,
   "name" : "Eliot",
   "reportsTo" : "Dev",
   "reportingHierarchy" : [
      { "_id" : 1, "name" : "Dev" }
   ]
}
{
   "_id" : 3,
   "name" : "Ron",
   "reportsTo" : "Eliot",
   "reportingHierarchy" : [
      { "_id" : 1, "name" : "Dev" },
      { "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" }
   ]
}
{
   "_id" : 4,
   "name" : "Andrew",
   "reportsTo" : "Eliot",
   "reportingHierarchy" : [
      { "_id" : 1, "name" : "Dev" },
      { "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" }
   ]
}
{
   "_id" : 5,
   "name" : "Asya",
   "reportsTo" : "Ron",
   "reportingHierarchy" : [
      { "_id" : 1, "name" : "Dev" },
      { "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" },
      { "_id" : 3, "name" : "Ron", "reportsTo" : "Eliot" }
   ]
}
{
   "_id" : 6,
   "name" : "Dan",
   "reportsTo" : "Andrew",
   "reportingHierarchy" : [
      { "_id" : 1, "name" : "Dev" },
      { "_id" : 2, "name" : "Eliot", "reportsTo" : "Dev" },
      { "_id" : 4, "name" : "Andrew", "reportsTo" : "Eliot" }
   ]
}

但是,假设我希望以嵌套文档而不是列表的形式显示结果,例如:

Dev
|-- Eliot
    |-- Ron
        |-- Asya
    |-- Andrew
        |--Dan

编辑2

子级是否位于数组中并不重要。只要嵌套完整的结构,以下任何一项都可以:

{ 
  "_id" : 1, 
  "name" : "Dev",
  "children" : [
    {
       "_id" : 1, 
       "name" : "Eliot",
       "children": [...]
    }
  ]
}

{ 
  "_id" : 1, 
  "name" : "Dev",
  "children" : {
    {
       "_id" : 1, 
       "name" : "Eliot",
       "children": {...}
    }
  }
}

0 个答案:

没有答案