Is this working?
In computer science when we say Graph we mean dots and dashes
.... . .-.. .-.. --- / .-- --- .-. .-.. -..
Oh, wait that's the morse code. Let's try this again, shall we?
What is a Graph?
Spoiler alert: You shouldn't. It's not worth it. Leave while you can. We're going into a rabbit hole.
Let's take a look at a few examples.
Btw this whole talk is totally not a rip off from MongoDB's official blog
User:
- Name: String
- Friends: Array of strings
[
{
"name": "Bob",
"friends": ["Alice", "Kate"]
},
{
"name": "Alice",
"friends": ["Bob", "John"]
},
{
"name": "Kate",
"friends": ["Bob"]
},
{
"name": "John",
"friends": ["Alice"]
}
]
db.people.find({ friends: "Bob", name: { $ne: "Kate" }})
{
_id: ObjectId("63cb73f1bb0776fa5f0fd497"),
name: 'Alice',
friends: [
'Bob',
'John'
]
}
Fortunately for us, we don't need to install a graph DB for simple queries like the one above.
MongoDB has an aggreation operator called $graphLookup
.
db.people.aggregate([
{ $match: { name: "Kate", } },
{
$graphLookup: {
from: "people",
startWith: "$friends",
connectFromField: "friends",
connectToField: "name",
as: "network",
depthField: "connectionLevel",
maxDepth: 2,
restrictSearchWithMatch: { name: { $ne: "Kate" } }
},
},
{
$project: { name: 1, network: 1 }
}
])
Alright, let's break it down
$match.name: "Kate"
startsWith
and looks for that value
in the colleciton in from
field.Image courtesy: Entgo
Hope you've got some idea to include $graphLookup in your projects.
If you have any questions ask ChatGPT me.