Skip to content

Instantly share code, notes, and snippets.

@gaarf
Created July 12, 2012 00:46
Show Gist options
  • Save gaarf/3094814 to your computer and use it in GitHub Desktop.
Save gaarf/3094814 to your computer and use it in GitHub Desktop.
mongoose mapreduce (public)
SomeSchema.methods.mapReduce = function(callback) {
function map() {
/*global emit:true */
emit('something', {foos:this.foos, users:1});
}
function reduce(k, av) {
var foos = 0;
av.forEach(function(v) {
foos += v.foos;
});
return {foos:foos, users:av.length};
}
function finalize(k, v) {
v.average = Math.floor(v.foos / v.users);
return v;
}
var command = {
mapreduce : 'collection_name'
, query: {bar:{$gt: 9}} // we iterate over docs in collection_name with bar>9
, out: { inline: 1 }
, map: map.toString()
, reduce: reduce.toString()
, finalize: finalize.toString()
};
mongoose.connection.db.executeDbCommand(command, function(err, dbres) {
var out = {foos:0, users:0, average:0}; // this is my default output
try { out = dbres.documents[0].results[0].value; } catch(e) {}
callback(err, out);
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment