21. Recursive Relationships with $graphLookup

$graphLookup recursively follows relationships in a collection, making it useful for employee hierarchies, category trees, dependency graphs, and referral networks.

Important options include from, startWith, connectFromField, connectToField, as, maxDepth, depthField, and restrictSearchWithMatch. Recursive traversal can expand rapidly, so use appropriate depth limits, indexes, and representative tests. For frequently queried hierarchies, a materialized path or ancestor array may be a better model.

Create the example hierarchy first

The example assumes an employees collection with _id, name, and managerId fields.

Code Example
db.employees.aggregate([
  { $match: { _id: 100 } },
  {
    $graphLookup: {
      from: "employees",
      startWith: "$_id",
      connectFromField: "_id",
      connectToField: "managerId",
      as: "reports",
      maxDepth: 4,
      depthField: "hierarchyDepth"
    }
  },
  { $project: { name: 1, reports: 1 } }
]);
Key Takeaways
  • $graphLookup traverses recursive relationships.
  • Results are returned in an array.
  • Depth limits can control traversal.
  • Consider alternate hierarchy models for frequent reads.
Knowledge Check

Which option limits recursive traversal depth?