Simulated example. Two mongodb collections, departments
and employees
:
Departments
{ _id: '101' }
{ _id: '102', parent: '101' }
{ _id: '103', parent: '101' }
{ _id: '104', parent: '103' }
Employees
{ _id: '201', department: '101' }
{ _id: '202', department: '102' }
{ _id: '203', department: '102' }
{ _id: '204', department: '103' }
{ _id: '205', department: '104' }
How can I query a list of all employees in a department, or any sub department (by the department.parent
reference property)?
So for the above example, querying for:
- department
101
should give employee documents201, 202, 203, 204, 205
- department
102
should give employee documents202, 203, 204, 205
- department
103
should give employee documents204, 205
If it is not possible to make a query for "any number" of levels in the department tree, one that gives the results for "up to N" levels is fully acceptable.