0
0
MongoDBquery~5 mins

Graph lookup for recursive data in MongoDB

Choose your learning style9 modes available
Introduction

Graph lookup helps find connected data that links to itself, like family trees or company hierarchies.

You want to find all employees under a manager in a company.
You need to get all parts that make up a product, including parts of parts.
You want to explore all friends of a person in a social network.
You want to find all categories inside a main category in a store.
You want to trace all ancestors or descendants in a family tree.
Syntax
MongoDB
db.collection.aggregate([
  {
    $graphLookup: {
      from: "collectionName",
      startWith: "$fieldToStart",
      connectFromField: "fieldToFollow",
      connectToField: "fieldToMatch",
      as: "outputArray",
      maxDepth: <number>,          // optional
      depthField: "depthFieldName" // optional
    }
  }
])

from is the collection to search recursively.

startWith is the value to start the search from.

Examples
Finds all employees under each manager recursively.
MongoDB
db.employees.aggregate([
  {
    $graphLookup: {
      from: "employees",
      startWith: "$managerId",
      connectFromField: "employeeId",
      connectToField: "managerId",
      as: "subordinates"
    }
  }
])
Finds subcategories up to 3 levels deep and adds a level field.
MongoDB
db.categories.aggregate([
  {
    $graphLookup: {
      from: "categories",
      startWith: "$_id",
      connectFromField: "_id",
      connectToField: "parentId",
      as: "allSubcategories",
      maxDepth: 3,
      depthField: "level"
    }
  }
])
Finds all parts that make up a product recursively.
MongoDB
db.products.aggregate([
  {
    $graphLookup: {
      from: "products",
      startWith: "$componentId",
      connectFromField: "_id",
      connectToField: "componentId",
      as: "allComponents"
    }
  }
])
Sample Program

This inserts employees with managers and finds all subordinates for each employee recursively.

MongoDB
db.employees.insertMany([
  { employeeId: 1, name: "Alice", managerId: null },
  { employeeId: 2, name: "Bob", managerId: 1 },
  { employeeId: 3, name: "Charlie", managerId: 1 },
  { employeeId: 4, name: "David", managerId: 2 },
  { employeeId: 5, name: "Eve", managerId: 2 }
])

// Find all subordinates under each employee

const result = db.employees.aggregate([
  {
    $graphLookup: {
      from: "employees",
      startWith: "$managerId",
      connectFromField: "employeeId",
      connectToField: "managerId",
      as: "subordinates"
    }
  }
]).toArray()

printjson(result)
OutputSuccess
Important Notes

Time complexity depends on the size and depth of the graph.

Space complexity grows with the number of connected documents found.

Common mistake: mixing up connectFromField and connectToField causes no results.

Use $graphLookup when you need recursive search; use $lookup for simple joins.

Summary

$graphLookup helps find connected data recursively in the same collection.

It is useful for hierarchical or network data like employees or categories.

Remember to set correct fields for starting point and connections.