【问题标题】:MongoDB: $graphLookup in reverse orderMongoDB:以相反的顺序 $graphLookup
【发布时间】:2019-03-27 08:22:42
【问题描述】:

我有以下数据集:

{
  _id: ObjectId("asdasdasd..."),
  dependencies: {
    customers: [
      ObjectId("1..."),
      ObjectId("2...")
    ]
  }
}

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

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

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

是否有可能以某种方式查看所有依赖于树中最后一个客户的客户?

例如 普通的 GraphLookup: C1 => C2 => C3 => ...

反向GraphLookup: C3 => C2 => C1

也许我需要更改架构...但我不知道如何。

另一种选择是存储 2 种不同类型的依赖项:父项、子项。但这使得所有更改都需要进行两次:对于在父项中具有依赖项 X 的客户和在子项中具有依赖项 X 的客户。

有什么想法吗?

【问题讨论】:

  • 你有没有找到一个好的解决方案?
  • 对不起。到目前为止:没有

标签: mongodb


【解决方案1】:

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

{
  _id: ObjectId("asdasdasd..."),
  dependencies: {
    customers: [
      ObjectId("1..."),
      ObjectId("2...")
    ],
    customersOf: [
      ObjectId("1..."),
      ObjectId("2...")
    ],
  }
}

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

// 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,
  }
}])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-18
    • 2023-03-31
    • 1970-01-01
    • 2016-09-20
    • 2015-02-17
    • 1970-01-01
    • 2016-10-05
    • 2011-11-02
    相关资源
    最近更新 更多