使用 MongoDB 的 $graphLookup 时出现问题

Problems using MongoDB's $graphLookup

我有两个collections。 sources:

[
  {
    "_id": "0001",
    "name": "John Doe"
  },
  {
    "_id": "0002",
    "address": "123 Some Place"
  },
  {
    "_id": "0003",
    "phone": "5555555555"
  }
]

connections

[
  {
    "_id": "0001.0002",
    "_from": "0001",
    "_to": "0002",
    "probability": 0.8
  },
  {
    "_id": "0002.0003",
    "_from": "0002",
    "_to": "0003",
    "probability": 0.6
  }
]

我正在尝试使用 $graphLookup 进行图形遍历以获取所有源连接的列表。这是我的代码:

db.sources.aggregate([
    {
      $match: {
        '_id': '0001'
      }
    },
    {
      $graphLookup: {
        from: 'connections',
        startWith: '_id',
        connectFromField: '_from',
        connectToField: '_to',
        maxDepth: 2,
        depthField: 'numConnections',
        as: 'destinations'
      }
    }
])

这个returnsdestinations数组就是空的。我希望它包含两条记录(0002 和 0003)。

我还想在遍历期间乘以概率,以便 0001 -> 0002 = 0.8 和 0001 -> 0003 = 0.48 (0.8 * 0.6)。我一定是在这里遗漏了一些简单的东西,因为我试图准确地遵循它在文档中的表示方式 (https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/)。

您可以尝试以下查询。

您将需要两个 $graphlookup,一个用于每个源的连接,另一个用于计算每个连接的概率。

$unwind$graphlookup 以获得每个连接的所有概率。

$reduce to $multiply 每个集合的所有数组元素。

$group 将源文档与各自的联系及其概率分组。

db.sources.aggregate([
  {
    "$match": {
      "_id": "0001"
    }
  },
  {
    "$graphLookup": {
      "from": "connections",
      "startWith": "$_id",
      "connectFromField": "_to",
      "connectToField": "_from",
      "maxDepth": 2,
      "depthField": "numConnections",
      "as": "destinations"
    }
  },
  {
    "$unwind": "$destinations"
  },
  {
    "$graphLookup": {
      "from": "connections",
      "startWith": "$destinations._to",
      "connectFromField": "_from",
      "connectToField": "_to",
      "maxDepth": 2,
      "as": "destinations.probabilities"
    }
  },
  {
    "$addFields": {
      "destinations.probabilities": {
        "$reduce": {
          "input": "$destinations.probabilities.probability",
          "initialValue": 1,
          "in": {
            "$multiply": [
              "$$value",
              "$$this"
            ]
          }
        }
      }
    }
  },
  {
    "$group": {
      "_id": "$_id",
      "name": {
        "$first": "$name"
      },
      "destinations": {
        "$push": "$destinations"
      }
    }
  }
])