$graphLookup (Graph Lookup)
Last updated: 2026-10-09
$graphLookup (Graph Lookup)
$graphLookup performs recursive searches on a collection, emulating graph traversal: starting from connectFromField values, it recursively matches connectToField until maxDepth or no more matches, storing results in as. Ideal for org charts, category trees, and hop counting. Unlike $lookup, it recurses across arbitrary depth.
| Category | Advanced & Diagnostic |
|---|---|
| MongoDB Version | 1.0+ |
| Example Language | mongosh (Shell) |
📝 Syntax
{ $graphLookup: { from: "<collection>", startWith: <expression>, connectFromField: "<field>", connectToField: "<field>", as: "<outputField>", maxDepth: <number>, depthField: "<depthField>" } }
⚙️ Parameters
| from | Target collection for recursive searches. |
|---|---|
| startWith | Expression for the value that starts the recursion. |
| connectFromField | Field on the current document holding the matching value. |
| connectToField | Field on the target collection that gets matched. |
| as | Field name that receives the recursion results. |
| maxDepth | Maximum recursion depth; unlimited when omitted. |
Returns:Each document augmented with a recursion result array
▶ Example
Run the commands below in your local mongosh (requires a running mongod):
// $graphLookup: build the reporting chain per employee
db.employees.aggregate([
{ $graphLookup: {
from: 'employees',
startWith: '$reportsTo',
connectFromField: 'reportsTo',
connectToField: 'name',
as: 'chain'
} }
])
Output:
// Each employee document gains a chain array of managers
📌 Notes
- Index connectToField to speed up recursion
- Results include recursively matched documents, not the starting one
- maxDepth 0 matches only one level
🏷️ Related Tags
💡 Related Cases
More hands-on cases coming soon.
📚 Related Tutorials
❓ FAQ
QWhat is the difference between $graphLookup and $lookup?
A$lookup joins one level; $graphLookup recurses across many levels.
QCan recursion loop forever?
AIt recurses until no matches remain; cap it with maxDepth.
QDoes the result include the document itself?
ANo. startWith is the seed; results are other documents that match it.