Example 1 — Sample Data
Seven employees. Each person (except Alice) points reportsTo at their manager’s _id.
db.employees.drop()
db.employees.insertMany([
{ _id: 1, name: "Alice Chen", title: "VP Engineering", reportsTo: null, active: true },
{ _id: 2, name: "Bob Smith", title: "Eng Manager", reportsTo: 1, active: true },
{ _id: 3, name: "Carol Diaz", title: "Eng Manager", reportsTo: 1, active: true },
{ _id: 4, name: "Dave Kim", title: "Senior Dev", reportsTo: 2, active: true },
{ _id: 5, name: "Eve Patel", title: "Dev", reportsTo: 2, active: true },
{ _id: 6, name: "Frank Lee", title: "Senior Dev", reportsTo: 3, active: true },
{ _id: 7, name: "Grace Wu", title: "Intern", reportsTo: 4, active: false }
])
// Index the field you match during the walk
db.employees.createIndex({ reportsTo: 1 }) How the Data Is Stored in MongoDB
After the insert, MongoDB keeps seven documents in employees. Run find() to see them:
db.employees.find().sort({ _id: 1 }) Read the important fields like this:
| Field | Example | Plain English |
|---|---|---|
_id | 2 | Employee id (connectFromField) |
reportsTo | 1 | Manager id (connectToField) |
name | "Bob Smith" | Display label in results |
How It Works
- Parent pointer. Children store the manager id in
reportsTo. - Alice is the root. Her
reportsToisnull. - Index helps.
reportsTois what each hop queries.

