如何使用 MongoDB 的 $graphLookup 获取所有子文档

How to get all children documents using $graphLookup of MongoDB

我在 MongoDB 的两个集合中有如下数据。 类别:

[
  { "_id" : 1, "name" : "A" },
  { "_id" : 2, "name" : "B", "categoryId" : 1 },
  { "_id" : 3, "name" : "C", "categoryId" : 1 },
  { "_id" : 4, "name" : "D", "categoryId" : 2 },
  { "_id" : 5, "name" : "E", "categoryId" : 3 },
  { "_id" : 6, "name" : "F", "categoryId" : 2 }
];

我有 Locos 个文档:

[
  { "_id" : 1, "name" : "X", "categoryId" : 2 },
  { "_id" : 2, "name" : "Y", "categoryId" : 3 },
  { "_id" : 2, "name" : "B", "categoryId" : 1 } 
]

例如,如果我想获得 ID 为 1 的类别 A 的所有子项,我将调用该函数并将其returns 一组儿童类别的 ID,如果可能的话还有 Locos 儿童。所以结果会是这样的:

chilren: {
          categories: [2, 3, 4, 5, 6],
          locos: [1, 2, 3]
         }

如果我调用 ID 为 2 的函数,类别为 B,我得到的结果是:

chilren: {
          categories: [2, 6],
          locos: [1]
         }

您的使用方向正确$graphLookup

db.categories.aggregate([
  {
    "$match": {
      _id: 1
    }
  },
  {
    "$graphLookup": {
      "from": "categories",
      "startWith": "$_id",
      "connectFromField": "_id",
      "connectToField": "categoryId",
      "as": "categoryLookup"
    }
  },
  {
    "$graphLookup": {
      "from": "locos",
      "startWith": "$_id",
      "connectFromField": "_id",
      "connectToField": "categoryId",
      "as": "locosLookup"
    }
  },
  {
    "$project": {
      children: {
        categories: {
          "$map": {
            "input": "$categoryLookup",
            "as": "c",
            "in": "$$c._id"
          }
        },
        locos: {
          "$map": {
            "input": "$locosLookup",
            "as": "l",
            "in": "$$l._id"
          }
        }
      }
    }
  }
])

这里是Mongo playground供您参考。