Created
July 12, 2012 00:46
-
-
Save gaarf/3094814 to your computer and use it in GitHub Desktop.
mongoose mapreduce (public)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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