使用MongoDB的$ graphLookup时出现问题

时间:2017-11-30 16:56:03

标签: mongodb graph-traversal

我有两个系列。 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'
      }
    }
])

这将返回空的destinations数组。我希望它包含两个记录(0002和0003)。

我还希望在遍历期间增加概率,以便0001-> 0002 = 0.8和0001 - > 0003 = 0.48(0.8 * 0.6)。我必须在这里遗漏一些简单的东西,因为我试图完全按照它在文档中的表示(https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/)。

1 个答案:

答案 0 :(得分:4)

您可以尝试以下查询。

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

<{> 3} $unwind $graphlookup以获得每个连接的所有概率。

$reduce$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"
      }
    }
  }
])