如何编写查找多个路径的MongoDB查询

dfty9e19  于 2022-12-18  发布在  Go
关注(0)|答案(1)|浏览(121)

bounty将在23小时后过期。回答此问题可获得+50的信誉奖励。Vladimir Djukic正在寻找来自信誉良好来源的答案:我需要的代码,将解决这2个问题,我提到的问题:

  • 只过滤以所需元素结束的路径-每个路径都需要分开
    以下是我正在处理的集合:
- sign1: A1
- sign2: A2

- sign1: A2
- sign2: A5

- sign1: A2
- sign2: A6

- sign1: A2
- sign2: A8

- sign1: A5
- sign2: A8

查询应查找从A1到A8的路径
例如,它应查明:

path1:
A1 A2 -> A2 A5 -> A5 A8

path2:
A1 A2 -> A2 A8

path3:
A1 A2 -> A2 A6 -> should be ignored since not finishes with A8

目前,我尝试了这个(部分解决方案由@ray):
My Query
我的查询的第一个问题是,即使不是以A8结尾,它也会返回所有路径
第二个问题是不分隔路径会将所有内容放在一个数组中

ghhaqwfi

ghhaqwfi1#

要过滤并仅返回以A8结尾的路径,您必须在$graphLookup之后再次使用$match stage**。
您可以尝试类似这样的操作,仅返回以A8结尾的路径

db.collection.aggregate([
  {
    "$match": {
      sign1: "A1"
    }
  },
  {
    "$graphLookup": {
      "from": "collection",
      "startWith": "$sign1",
      "connectFromField": "sign2",
      "connectToField": "sign1",
      "as": "path",
      "depthField": "step"
    }
  },
  {
    "$match": {
      "path.sign2": "A8"
    }
  }
])

现在,如果您想将路径分隔到不同的数组/文档中,则必须在$match阶段之前使用$unwind stage,如下所示:

db.collection.aggregate([
  {
    "$match": {
      sign1: "A1"
    }
  },
  {
    "$graphLookup": {
      "from": "collection",
      "startWith": "$sign1",
      "connectFromField": "sign2",
      "connectToField": "sign1",
      "as": "path",
      "depthField": "step"
    }
  },
  {
    "$unwind": "$path"
  },
  {
    "$match": {
      "path.sign2": "A8"
    }
  }
])

EDITED:如果您想过滤掉不需要的路径或step等于0的路径,您可以在$graphLookup阶段使用$filter操作,如下所示,根据这两个条件返回结果。

db.collection.aggregate([
  {
    "$match": {
      sign1: "A1"
    }
  },
  {
    "$graphLookup": {
      "from": "collection",
      "startWith": "$sign1",
      "connectFromField": "sign2",
      "connectToField": "sign1",
      "as": "path",
      "depthField": "step",
      "maxDepth": 10,
      "filter": {
        "$and": [
          { "step": { "$gt": 0 } },
          { "sign2": "A8" }
        ]
      }
    }
  },
  {
    "$unwind": "$path"
  }
])

相关问题