To filter and return only the paths that end with A8
you will have to use the $match stage again after the $graphLookup
.
You can try something like this to return only paths that end with A8
db.collection.aggregate([
{
"$match": {
sign1: "A1"
}
},
{
"$graphLookup": {
"from": "collection",
"startWith": "$sign1",
"connectFromField": "sign2",
"connectToField": "sign1",
"as": "path",
"depthField": "step"
}
},
{
"$match": {
"path.sign2": "A8"
}
}
])
Now, if you want to separate the paths into different arrays/documents you will have to use the $unwind stage before the $match
stage like this:
db.collection.aggregate([
{
"$match": {
sign1: "A1"
}
},
{
"$graphLookup": {
"from": "collection",
"startWith": "$sign1",
"connectFromField": "sign2",
"connectToField": "sign1",
"as": "path",
"depthField": "step"
}
},
{
"$unwind": "$path"
},
{
"$match": {
"path.sign2": "A8"
}
}
])
EDITED:
If you want to filter the undesired paths or the ones that have step
equal to 0 you can use the $filter
operation in your $graphLookup
stage like this, to return results based on those two conditions.
db.collection.aggregate([
{
"$match": {
sign1: "A1"
}
},
{
"$graphLookup": {
"from": "collection",
"startWith": "$sign1",
"connectFromField": "sign2",
"connectToField": "sign1",
"as": "path",
"depthField": "step",
"maxDepth": 10,
"filter": {
"$and": [
{ "step": { "$gt": 0 } },
{ "sign2": "A8" }
]
}
}
},
{
"$unwind": "$path"
}
])