我需要在可空字段上执行graphLookUp。在本例中,我有一个“节点”集合,其中"name“和"connectsTo”可能都为空,但如果它们都为空,则不应将其视为有效连接:
{ _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" }这张图是这样的:
1 <- 2 <- 3 <- 4
<- 5
6 <- 74、5和7都有空名。
我希望从1得到节点的层次结构,并排除从1断开连接的任何节点。
我尝试过这样的查询:
db.nodes.aggregate([
{ $match: { _id: 1 } },
{ $graphLookup: {
from: "nodes",
startWith: "$name",
connectFromField: "name",
connectToField: "connectsTo",
as: "hierarchy",
depthField: "depth"
}}
]).pretty()然而,这产生了以下结果:
{
"_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的节点之后立即终止层次结构?
发布于 2020-11-25 11:07:28
答案是使用restrictSearchWithMatch并排除connectsTo不为空的地方。由于这会在与节点匹配时终止递归,这就排除了6(它有一个空connectsTo),然后也排除了7,因为7现在与图断开连接:
db.nodes.aggregate([
{ $match: { _id: 1 } },
{ $graphLookup: {
from: "nodes",
startWith: "$name",
connectFromField: "name",
connectToField: "connectsTo",
as: "hierarchy",
depthField: "depth"
restrictSearchWithMatch: {
connectsTo: { $ne: null }
}
}}
]).pretty()https://stackoverflow.com/questions/65002992
复制相似问题