$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.

CategoryAdvanced & Diagnostic
MongoDB Version1.0+
Example Languagemongosh (Shell)

📝 Syntax

{ $graphLookup: { from: "<collection>", startWith: <expression>, connectFromField: "<field>", connectToField: "<field>", as: "<outputField>", maxDepth: <number>, depthField: "<depthField>" } }

⚙️ Parameters

fromTarget collection for recursive searches.
startWithExpression for the value that starts the recursion.
connectFromFieldField on the current document holding the matching value.
connectToFieldField on the target collection that gets matched.
asField name that receives the recursion results.
maxDepthMaximum 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏