首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MongoDB:逆序$graphLookup

MongoDB:逆序$graphLookup
EN

Stack Overflow用户
提问于 2017-05-04 21:57:09
回答 1查看 1K关注 0票数 2

我有以下数据集:

代码语言:javascript
复制
{
  _id: ObjectId("asdasdasd..."),
  dependencies: {
    customers: [
      ObjectId("1..."),
      ObjectId("2...")
    ]
  }
}

我使用"$graphLookup“来查看所有相互关联的客户。

代码语言:javascript
复制
db.getCollection('customers').aggregate([{
  $graphLookup: {
    from: "customers",
    startWith: "$dependencies.customers",
    connectFromField: "dependencies.customers",
    connectToField: "_id",
    depthField: "depth",
    as: "dependencies.customers",
    maxDepth: 5,
  }
}])

这一切都很好。但现在我想以相反的顺序查看图表。依赖关系树中的最后一个客户与其他客户没有其他依赖关系。当然,否则我不会是那棵树上的最后一个顾客。

有没有可能看到所有依赖于树中最后一个客户的客户?

例如normal GraphLookup: C1 => C2 => C3 => ...

reverse GraphLookup: C3 => C2 => C1

也许我需要改变模式。但我不知道怎么做。

另一种选择是存储两种不同类型的依赖项:父项、子项。但这使得所有的更改都必须做两次:对于父对象中具有依赖关系X的客户和在子对象中具有依赖关系X的客户。

有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2019-03-27 08:22:42

您的数据需要指明关系的方向(例如parent=>child或child=>parent )。我看到的方法是将数据存储在指示关系的数组中。对于你来说,应该是这样的:

代码语言:javascript
复制
{
  _id: ObjectId("asdasdasd..."),
  dependencies: {
    customers: [
      ObjectId("1..."),
      ObjectId("2...")
    ],
    customersOf: [
      ObjectId("1..."),
      ObjectId("2...")
    ],
  }
}

这样您就可以在每个方向上遍历数据。

代码语言:javascript
复制
// get customers
db.getCollection('customers').aggregate([{
  $graphLookup: {
    from: "customers",
    startWith: "$dependencies.customers",
    connectFromField: "dependencies.customers",
    connectToField: "_id",
    depthField: "depth",
    as: "dependencies.customers",
    maxDepth: 5,
  }
}])


// get customersOf (reverse direction)
db.getCollection('customers').aggregate([{
  $graphLookup: {
    from: "customers",
    startWith: "$dependencies.customersOf",
    connectFromField: "dependencies.customersOf",
    connectToField: "_id",
    depthField: "depth",
    as: "dependencies.customersOf",
    maxDepth: 5,
  }
}])
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43784935

复制
相关文章

相似问题

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