Skip to content

Instantly share code, notes, and snippets.

@abruzzi
Created October 7, 2015 12:18
Show Gist options
  • Save abruzzi/16a8eaf1252ff8716118 to your computer and use it in GitHub Desktop.
Save abruzzi/16a8eaf1252ff8716118 to your computer and use it in GitHub Desktop.
Map/Reduce in mongodb
var mapStaff = function() {
var values = {
department: this.department,
grade: this.grade,
role: this.role,
gender: this.gender,
preferredName: this.preferredName,
loginName: this.loginName,
hireDate: this.hireDate,
totalExperience: this.totalExperience,
twExperience: this.twExperience,
assignable: this.assignable,
homeOffice: this.homeOffice,
workingOffice: this.workingOffice
};
emit(this.employeeId, values);
}
var mapSkill = function() {
var values = {skills: this.skills};
emit(this.employeeId, values);
}
var reduce = function(k, values) {
var result = {};
values.forEach(function(value) {
var field;
for (field in value) {
if (value.hasOwnProperty(field)) {
result[field] = value[field];
}
}
});
return result;
};
db.staff.mapReduce(mapStaff, reduce, {"out": {"reduce": "staff_skills"}});
db.skills.mapReduce(mapSkill, reduce, {"out": {"reduce": "staff_skills"}});
db.staff_skills.find().pretty();

purpose

I have a collection which contains items in the following structure:

{
	"_id" : ObjectId("55efa44a23588e5686f045e7"),
	"gender" : "Male",
	"preferredName" : "Alan Turning",
	"hireDate" : "2013-06-04",
	"totalExperience" : 4.27,
	"employeeId" : "00001"
}

and also I have another collection like this:

{
	"_id" : ObjectId("55efd19123588e5686f054b7"),
	"skills" : [ ],
	"employeeId" : "00001"
}

and I want to merge those two collection as :

{
	"_id" : ObjectId("55efa44a23588e5686f045e7"),
	"gender" : "Male",
	"preferredName" : "Alan Turning",
	"hireDate" : "2013-06-04",
	"totalExperience" : 4.27,
	"employeeId" : "00001",
	"skills": []
}

in file map-reduce.js, I defined two map function and one reduce function to do this, the result is putting into staff_skills collection.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment