首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何执行排除空连接的graphLookUp?

如何执行排除空连接的graphLookUp?
EN

Stack Overflow用户
提问于 2020-11-25 10:40:21
回答 1查看 110关注 0票数 0

我需要在可空字段上执行graphLookUp。在本例中,我有一个“节点”集合,其中"name“和"connectsTo”可能都为空,但如果它们都为空,则不应将其视为有效连接:

代码语言:javascript
复制
{ _id: 1, name: "1", connectsTo: null }
{ _id: 2, name: "2", connectsTo: "1" }
{ _id: 3, name: "3", connectsTo: "2" }
{ _id: 4, name: null, connectsTo: "3" }
{ _id: 5, name: null, connectsTo: "3" }
{ _id: 6, name: "6", connectsTo: null }
{ _id: 7, name: null, connectsTo: "6" }

这张图是这样的:

代码语言:javascript
复制
1 <- 2 <- 3 <- 4
            <- 5
6 <- 7

4、5和7都有空名。

我希望从1得到节点的层次结构,并排除从1断开连接的任何节点。

我尝试过这样的查询:

代码语言:javascript
复制
db.nodes.aggregate([
  { $match: { _id: 1 } },
  { $graphLookup: {
      from: "nodes",
      startWith: "$name",
      connectFromField: "name",
      connectToField: "connectsTo",
      as: "hierarchy",
      depthField: "depth"
  }}
]).pretty()

然而,这产生了以下结果:

代码语言:javascript
复制
{
    "_id" : 1,
    "name" : "1",
    "connectsTo" : null,
    "hierarchy" : [
        { "_id" : 7, "name" : null, "connectsTo" : "6",  "depth" : NumberLong(4) },
        { "_id" : 1, "name" : "1",  "connectsTo" : null, "depth" : NumberLong(3) },
        { "_id" : 6, "name" : "6",  "connectsTo" : null, "depth" : NumberLong(3) },
        { "_id" : 5, "name" : null, "connectsTo" : "3",  "depth" : NumberLong(2) },
        { "_id" : 4, "name" : null, "connectsTo" : "3",  "depth" : NumberLong(2) },
        { "_id" : 3, "name" : "3",  "connectsTo" : "2",  "depth" : NumberLong(1) },
        { "_id" : 2, "name" : "2",  "connectsTo" : "1",  "depth" : NumberLong(0) }
    ]
}

如你所见,7和6都存在。我怀疑发生的情况是,6的空connectsTo正与空名称4或5匹配。

如何在名称为null的节点之后立即终止层次结构?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-25 11:07:28

答案是使用restrictSearchWithMatch并排除connectsTo不为空的地方。由于这会在与节点匹配时终止递归,这就排除了6(它有一个空connectsTo),然后也排除了7,因为7现在与图断开连接:

代码语言:javascript
复制
db.nodes.aggregate([
  { $match: { _id: 1 } },
  { $graphLookup: {
      from: "nodes",
      startWith: "$name",
      connectFromField: "name",
      connectToField: "connectsTo",
      as: "hierarchy",
      depthField: "depth"
      restrictSearchWithMatch: {
        connectsTo: { $ne: null }
      }
  }}
]).pretty()
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65002992

复制
相关文章

相似问题

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