I am looking for how to use $graphLookup
and its match condition to return all nodes until a condition is met, including matches breaks the condition in the recursion stack. the first node that satisfies the condition in the recursion stack on each separate branch.
This should work for an arbitrary topology.
EDIT: as Asya highlights, it's the first time that the condition is satisfied on each branch, and not on the entire recursion stack.
Example (note: "_id" fields in docs are omitted for brevity):
Data:
[
{
"key": 1,
"parent": null,
"name": "tom"
},
{
"key": 2,
"parent": 1,
"name": "tom"
},
{
"key": 3,
"parent": 2,
"name": "jack"
},
{
"key": 4,
"parent": 3,
"name": "jonny"
},
{
"key": 5,
"parent": 1,
"name": "jack"
},
{
"key": 6,
"parent": 5,
"name": "jack"
}
]
Query:
db.collection.aggregate([
{
"$match": {
"parent": null
}
},
{
"$graphLookup": {
"from": "collection",
"startWith": "$key",
"connectFromField": "key",
"connectToField": "parent",
"as": "children",
"restrictSearchWithMatch": {
"name": "jack"
},
"matchType":"firstHitAlongEachBranch" // made-up option
}
}
])
Desired result:
[
{
"children": [
{
"key": 2,
"name": "tom",
"parent": 1
},
{
"key": 3,
"parent": 2,
"name": "jack"
},
{
"key": 5,
"parent": 1,
"name": "jack"
},
],
"key": 1,
"name": "tom",
"parent": null
}
]
The result returns only the first of the three nodes (as expected).
Thank you