首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用MongoDB的$graphLookup的问题

使用MongoDB的$graphLookup的问题
EN

Stack Overflow用户
提问于 2017-11-30 16:56:03
回答 1查看 2.5K关注 0票数 1

我有两个收藏品。sources

代码语言:javascript
复制
[
  {
    "_id": "0001",
    "name": "John Doe"
  },
  {
    "_id": "0002",
    "address": "123 Some Place"
  },
  {
    "_id": "0003",
    "phone": "5555555555"
  }
]

connections

代码语言:javascript
复制
[
  {
    "_id": "0001.0002",
    "_from": "0001",
    "_to": "0002",
    "probability": 0.8
  },
  {
    "_id": "0002.0003",
    "_from": "0002",
    "_to": "0003",
    "probability": 0.6
  }
]

我试图使用$graphLookup进行图遍历,以获得所有源连接的列表。这是我的代码:

代码语言:javascript
复制
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/)中准确地描述它的方式。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-12-04 18:55:16

您可以尝试以下查询。

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

$unwind$graphlookup一起获取每个连接的所有概率。

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

$group对具有各自连接及其概率的源文档进行分组。

代码语言:javascript
复制
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"
      }
    }
  }
])
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47578646

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档