Mongo graphLookup problem.
I want the num of degrees separation between jerry and superman, the answer should be 2.
In my bi-directional node structure, jerry is connected to lois, louis is connected to superman.
My data
{
"from" : "jerry",
"to" : "lois"
}
{
"from" : "lois",
"to" : "jerry"
}
{
"from" : "superman",
"to" : "lois"
}
{
"from" : "lois",
"to" : "superman"
}
The query below returns 4 documents with "degreeOfSeparation" : 4, this represent the bi-directional connections to superman.
db.getCollection("connections").aggregate([
{
$graphLookup : {
from: "connections",
startWith: "$from",
connectFromField: "from",
connectToField: "to",
maxDepth:5,
as: "connections"
}
},
{
$match: {
"connections.from": "jerry",
"connections.to": "superman"
}
},
{
$project: {
degreeOfSeparation: { $size: "$connections" }
}
}
2
Answers
This might works only on level of Grouped nodes
Mongodb playground
Here’s a way to get your
"degreeOfSeparation"
"from": "jerry"
"to": "superman"
and all of the degrees of separation using"$graphLookup"
‘s"depthField"
.Try it on mongoplayground.net.
Output using extended collection: