代码之家  ›  专栏  ›  技术社区  ›  darkfrog

使用MongoDB的$graphLookup时出现问题

  •  1
  • darkfrog  · 技术社区  · 8 年前

    我有两个收藏。 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 回复  |  直到 6 年前
        1
  •  5
  •   s7vr    8 年前

    您可以尝试以下查询。

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

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