-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsubtree.js
More file actions
64 lines (57 loc) · 1.94 KB
/
subtree.js
File metadata and controls
64 lines (57 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Map function to build department trees, essentially emits pairs
// {ancestor, dept} for each dept and each of its ancestors
function deptsMapfunc() {
if (this.ancestors != null) {
for(var i in this.ancestors) {
emit(this.ancestors[i], {"subdepts" : [this._id]});
}
} emit(this._id, {"subdepts" : []});
}
// Reduce function to build department trees, just gathers all the
// pairs from the map function into {dept, [list of depts in subtree]}
function reducefunc(key, values) {
var result = {"subdepts" : []};
for(var i in values) {
if (values[i] != null) {
if (values[i].subdepts != null) {
result.subdepts = result.subdepts.concat(values[i].subdepts);
}
}
}
return result;
}
// Executes the MapReduce call
function buildDeptTree() {
return db.depts.mapReduce(deptsMapfunc, reducefunc, {"out" : {"inline" : 1}});
}
// Goes over the department subtrees and adds the relevant employees to
// every entry.
// TODO: Look for a way to do this more efficient
function associateEmployees(resultObj) {
var result = [];
resultObj.results.forEach(function(elem) {
var deptsToSearch = elem.value.subdepts.concat(elem._id);
var singleResult = {
"_id" : elem._id,
"employees" : [],
"subdepts" : elem.value.subdepts
}; // Build return object
db.employees.find({"dept" : {$in : deptsToSearch}}).forEach(
function(ele) {
singleResult.employees = singleResult.employees.concat(ele._id);
}
);
result = result.concat(singleResult); // Find matching employees and add them to the result
});
return result;
}
// Main
var result = associateEmployees(buildDeptTree());
db.subtrees.drop();
db.createCollection("subtrees");
result.forEach(function(e) {
db.subtrees.insert(e);
});
result.forEach(function(e) {
printjson(e);
});