Graph Lookup for Recursive Data in MongoDB
📖 Scenario: You are managing a company's employee database. Each employee may have a manager, and managers themselves can have their own managers, forming a hierarchy. You want to find all the subordinates under a specific manager, including indirect reports.
🎯 Goal: Build a MongoDB aggregation query using $graphLookup to recursively find all employees reporting to a given manager.
📋 What You'll Learn
Create a MongoDB collection named
employees with documents containing _id, name, and manager_id fields.Add a variable
managerId to specify the starting manager's _id for the recursive search.Write an aggregation pipeline using
$graphLookup to find all employees reporting directly or indirectly to the manager with manager_id equal to managerId.Include the
subordinates field in the output documents containing the recursive results.💡 Why This Matters
🌍 Real World
Companies often need to query hierarchical employee data to understand reporting structures and manage teams effectively.
💼 Career
Knowing how to use recursive queries like <code>$graphLookup</code> in MongoDB is valuable for backend developers and data engineers working with hierarchical or graph data.
Progress0 / 4 steps