skip to content

How does $graphLookup traverse a hierarchy, and what do connectFromField and connectToField do?

level: seniorimportance: should knowfreq 38%

answer

  1. Repeat the join, don't do it once
  2. One field says where to go next
  3. Another says what to match on arriving
  4. The output is not shaped like a tree
  5. A number tells you how far each hop went

basics

~20 s

$graphLookup starts from the value in startWith, matches it against connectToField in the from collection, then takes connectFromField from each document it finds and repeats. All documents reached are returned flattened into one array named by as, with recursion capped by maxDepth.

solid answer

~50 s

`$graphLookup` is MongoDB's recursive join. `startWith` is an expression evaluated on the input document that supplies the first search value; that value is matched against `connectToField` on documents in `from`. For each document found, the value of its `connectFromField` becomes the next round's search value, and the process repeats until nothing new matches or `maxDepth` is reached. Everything reached across all rounds is returned **flattened into a single array** under `as` — not a nested tree, and in no guaranteed order. `depthField` adds a numeric recursion depth to each returned document, which is what you use to rebuild levels client-side, and `restrictSearchWithMatch` applies an additional query filter at every step. It handles cycles: already-visited documents are not re-traversed. Two operational constraints matter — `connectToField` should be indexed, and the past its 100 MB memory limit the stage spills to temporary files at MongoDB 9.0.4, or fails when `allowDiskUse` is `false`.

code

javascript · 13 lines
javascript
// Walk up: every manager above employee 42
db.employees.aggregate([
  { $match: { _id: 42 } },
  { $graphLookup: {
      from: "employees",
      startWith: "$managerId",
      connectFromField: "managerId",
      connectToField: "_id",
      as: "reportingChain",
      depthField: "level",
      maxDepth: 10
  } }
])

go deeper

for a junior

Know that $graphLookup exists for recursive parent-pointer traversal, and that it fills one array field with every document it reaches.

for a middle

Be able to name the roles: startWith seeds the search, connectToField is what you match on, connectFromField supplies the next hop, and depthField records how many hops it took.

for a senior

Interviewers expect the operational picture — index the connectToField, cap with maxDepth, prune with restrictSearchWithMatch, and know that the stage spills past 100 MB unless allowDiskUse is false, and that it can read a sharded from collection since 5.1.

for a principal

Own the modelling call: whether the hierarchy should be traversed on read at all, or carry a materialized ancestor path maintained on write, based on read/write ratio, tree depth and how often the structure changes.

## What it is for A hierarchy stored as `parentId` pointers — org charts, category trees, comment threads, bill-of-materials, follower graphs — cannot be resolved by `$lookup`, which does exactly one hop. `$graphLookup` performs the hop repeatedly, following the chain until it runs out. ```js db.employees.aggregate([ { $match: { _id: 42 } }, { $graphLookup: { from: "employees", startWith: "$managerId", connectFromField: "managerId", connectToField: "_id", as: "reportingChain", depthField: "level", maxDepth: 10 } } ]) ``` ## The recursion, one round at a time 1. **`startWith`** is an aggregation expression evaluated against the *input* document. Here it yields the employee's `managerId`. If it evaluates to an array, every element seeds the search. 2. That value is matched against **`connectToField`** on documents in **`from`** — round 0. The matched documents are added to the result. 3. For each newly matched document, the value of its **`connectFromField`** becomes a search value for round 1, again matched against `connectToField`. 4. Repeat until a round finds nothing new, or the depth reaches **`maxDepth`**. Swapping `connectFromField` and `connectToField` reverses the direction of travel. With `startWith: "$managerId"`, `connectFromField: "managerId"`, `connectToField: "_id"` you walk *up* to ancestors. With `startWith: "$_id"`, `connectFromField: "_id"`, `connectToField: "managerId"` you walk *down* to all descendants. Getting this pair backwards is the classic mistake and typically returns an empty array or just one document. ## The output is flat, not a tree This surprises people who expect a nested structure. `as` is a **single flat array** containing every document reached at every depth, deduplicated, in no defined order. If you need a tree, add `depthField` and reconstruct it in application code, or sort the array by depth. `depthField` numbers the first round **0**, so a direct manager is depth 0, the manager's manager is depth 1, and so on. `maxDepth` uses the same numbering — `maxDepth: 0` means "do the first lookup and stop", which makes it behave like a plain `$lookup`. ## Cycles A graph with a loop — A reports to B reports to A, a category that is its own ancestor — does not hang the stage. `$graphLookup` tracks what it has already visited and does not re-traverse it, so recursion terminates. That safety property is worth stating in an interview, because it is exactly the failure mode people fear from a recursive query. ## restrictSearchWithMatch This takes a **query document** (standard find-style syntax) applied at every step of the recursion, so you can traverse only active nodes or only nodes in one region. It is a filter on which documents may be *reached* — a node that fails the filter is not returned and is also not traversed *through*, which prunes whole subtrees. Note that it takes a query, not an aggregation expression, so you cannot use `$expr`-style comparisons against the outer document there. ## Cost and constraints - **Index `connectToField`.** Every round runs a lookup against it. Without an index each round is a collection scan, and the stage runs many rounds. - **Memory.** At MongoDB 9.0.4 the stage has a 100 MB memory limit and spills past it: its visited documents, visited values and queue go to temporary files, and `executionStats` explain reports `usedDisk` and the spill counters. With `allowDiskUse: false` the same traversal fails with `QueryExceededMemoryLimitNoDiskUseAllowed` instead. From 9.0 its memory also counts toward the per-operation memory limit. A wide traversal on a large graph therefore pays in disk I/O or fails — which makes `maxDepth` and `restrictSearchWithMatch` correctness *and* survivability tools, not just conveniences. - **Sharding.** The `from` collection for `$graphLookup` can be sharded since MongoDB 5.1, though the manual refuses that inside a transaction. - **Fan-out.** The result array lives inside one output document, so it is still subject to the 16 MB document limit. Traversing a highly connected graph from a hub node can breach it. ## When to reach for something else `$graphLookup` is excellent for bounded traversals: an ancestor chain a handful of levels deep, a subtree of moderate size, a two- or three-hop neighbourhood. It is not a graph engine — unbounded traversal over a densely connected graph is a poor fit for both its memory limit and its flat output. If the hierarchy is read constantly and changes rarely, storing a materialized ancestor path array on each document turns the whole traversal into a single indexed `find`, and `$graphLookup` becomes the tool you use to rebuild that path when the tree changes.

  • How would you change a $graphLookup that walks up to ancestors so it walks down to all descendants instead?
    Swap the direction of the pointer pair. Ancestors use `startWith: "$managerId"`, `connectFromField: "managerId"`, `connectToField: "_id"`. Descendants use `startWith: "$_id"`, `connectFromField: "_id"`, `connectToField: "managerId"` — you now match documents whose `managerId` points at the current node and follow their `_id` outward. The index requirement moves with it: index `managerId` for the descendant direction.
  • Does $graphLookup terminate if the hierarchy contains a cycle?
    Yes. It tracks the documents it has already visited and does not traverse them again, so a loop ends the recursion rather than running forever. Each document still appears at most once in the output array. Cycles do, however, make the depth numbers less meaningful, since a node reachable by two paths is recorded at the depth it was first reached.
  • What happens to a $graphLookup that needs more than the 100 MB stage memory limit?
    At MongoDB 9.0.4 it spills: the stage writes its visited set and queue to temporary files and keeps going, since `allowDiskUseByDefault` is true. With `allowDiskUse: false` it fails with `QueryExceededMemoryLimitNoDiskUseAllowed` instead. Spilling buys completion with disk I/O, so the practical response is still to constrain the traversal itself — set `maxDepth`, prune with `restrictSearchWithMatch`, or start from fewer seed documents by filtering hard before the stage.
  • Can $graphLookup join with a sharded collection?
    Yes, since MongoDB 5.1, as plain `$lookup` can, though the manual refuses it inside a multi-document transaction. Sharding does not make it cheap, because each round of the traversal queries the `from` collection again. On a hot path, materializing an ancestor path on each document turns the traversal into an ordinary indexed query.

  • Expects the output to be a nested tree
  • Swaps connectFromField and connectToField
  • Assumes a cyclic graph loops forever
  • Claims $graphLookup still ignores allowDiskUse on MongoDB 9.0
  • Believes maxDepth counts from 1

Assumes MongoDB 9.0.4, where the stage spills past its 100 MB limit, read from the source; earlier releases may fail instead of spilling, so check the manual for the server you run.

context