I am writing a map-reduce function in MongoDB that will be used across multiple collections. The result of the map-reduce on each collection merges the results into the same output collection.
I would like:
- To include the name of the collection that the document was from in the key so that the output collection contains a separate document if the same key was found in different source documents
- The map function to reference the name of the collection without hard coding it so that four different map functions don't have to be written for four collections that contain the same logic otherwise (i.e. keep the map function DRY)
Is this possible?
More detail below...
map function:
function() {
emit({ cpID: this.cpID, institutionID: this.institutionID, sourceCollection: collName }, 1);
};
reduce function:
function(key, values) {
return values.length;
};
mongo shell commands:
db.loadServerScripts();
var collName;
collName = "activities";
db.activities.mapReduce(mapcpsinstitutions, reducecpsinstitutions, { out: {replace: "cpsAndSchools"}, "scope": { "collName": collName } } );
collName = "activitysummaries";
db.activitysummaries.mapReduce(mapcpsinstitutions, reducecpsinstitutions, { out: {reduce: "cpsAndSchools"}, "scope": { "collName": collName } } );
collName = "contentusagesummaries";
db.contentusagesummaries.mapReduce(mapcpsinstitutions, reducecpsinstitutions, { out: {reduce: "cpsAndSchools"}, "scope": { "collName": collName } } );
collName = "contentusages";
db.contentusages.mapReduce(mapcpsinstitutions, reducecpsinstitutions, { out: {reduce: "cpsAndSchools"}, "scope": { "collName": collName } } );