如何列出树结构上MongoDB中的所有项目?

How to list all items in the MongoDB on the tree structure?

考虑这样的结构:

class Group {
  _id: ObjectId
  subGroups: ObjectId[]
  name: string
  info: string
}

数据库中 A 组的文档应该是...

_id: ObjectId("6092387f9c69970c20fe648a")
subGroups: [
  ObjectId("6092387f9c69970c20fe648b"),  // Group B
  ObjectId("6092387f9c69970c20fe648c"), // Group C
],
name: "Group A",
info: "..."

如何在 mongodb 中查询以获取包括其自身在内的所有子项?

例如,

查询 A:输出 A、B、C、D、E、F、G、H、I、J

查询 B:输出 D、E

您要使用的是 $graphLookup,它会递归迭代直到找不到更多匹配项,如下所示:

db.collection.aggregate([
  {
    $match: {
      "name": "Group A"
    }
  },
  {
    $graphLookup: {
      from: "collection",
      startWith: "$subGroups",
      connectFromField: "subGroups",
      connectToField: "_id",
      as: "groupHierarchy",
      
    }
  },
  {
    $project: {
      result: {
        "$concatArrays": [
          [
            "$name"
          ],
          {
            $map: {
              input: "$groupHierarchy",
              as: "group",
              in: "$$group.name"
            }
          }
        ]
      }
    }
  }
])

Mongo Playground