0
0
MongoDBquery~30 mins

Graph lookup for recursive data in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
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
1
Create the employees collection with sample data
Create a MongoDB collection called employees and insert these exact documents: { _id: 1, name: "Alice", manager_id: null }, { _id: 2, name: "Bob", manager_id: 1 }, { _id: 3, name: "Charlie", manager_id: 1 }, { _id: 4, name: "David", manager_id: 2 }, { _id: 5, name: "Eve", manager_id: 2 }.
MongoDB
Need a hint?

Use db.employees.insertMany() with an array of documents.

2
Define the managerId variable for the lookup
Create a variable called managerId and set it to 1 to represent the manager Alice's _id.
MongoDB
Need a hint?

Use const managerId = 1 to set the variable.

3
Write the aggregation pipeline with $graphLookup
Write an aggregation pipeline on employees that uses $match to find the document with _id equal to managerId, then uses $graphLookup to recursively find all employees where manager_id matches _id in the hierarchy. Store the results in a field called subordinates.
MongoDB
Need a hint?

Use $graphLookup with from, startWith, connectFromField, connectToField, and as fields.

4
Run the aggregation and assign the result
Run the aggregation pipeline on employees using aggregate(pipeline) and assign the result to a variable called result.
MongoDB
Need a hint?

Use const result = db.employees.aggregate(pipeline) to run the query.