mapreduce.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // import async to make control flow simplier
  2. var async = require('async');
  3. // import the rest of the normal stuff
  4. var mongoose = require('../../lib');
  5. require('./person.js')();
  6. var Person = mongoose.model('Person');
  7. // define some dummy data
  8. var data = [
  9. { name : 'bill', age : 25, birthday : new Date().setFullYear((new
  10. Date().getFullYear() - 25)), gender : "Male" },
  11. { name : 'mary', age : 30, birthday : new Date().setFullYear((new
  12. Date().getFullYear() - 30)), gender : "Female" },
  13. { name : 'bob', age : 21, birthday : new Date().setFullYear((new
  14. Date().getFullYear() - 21)), gender : "Male" },
  15. { name : 'lilly', age : 26, birthday : new Date().setFullYear((new
  16. Date().getFullYear() - 26)), gender : "Female" },
  17. { name : 'alucard', age : 1000, birthday : new Date().setFullYear((new
  18. Date().getFullYear() - 1000)), gender : "Male" },
  19. ];
  20. mongoose.connect('mongodb://localhost/persons', function (err) {
  21. if (err) throw err;
  22. // create all of the dummy people
  23. async.each(data, function (item, cb) {
  24. Person.create(item, cb);
  25. }, function (err) {
  26. // alright, simple map reduce example. We will find the total ages of each
  27. // gender
  28. // create the options object
  29. var o = {};
  30. o.map = function () {
  31. // in this function, 'this' refers to the current document being
  32. // processed. Return the (gender, age) tuple using emit()
  33. emit(this.gender, this.age);
  34. };
  35. // the reduce function receives the array of ages that are grouped by the
  36. // id, which in this case is the gender
  37. o.reduce = function (id, ages) {
  38. return Array.sum(ages);
  39. };
  40. // other options that can be specified
  41. // o.query = { age : { $lt : 1000 }}; // the query object
  42. // o.limit = 3; // max number of documents
  43. // o.keeptemp = true; // default is false, specifies whether to keep temp data
  44. // o.finalize = someFunc; // function called after reduce
  45. // o.scope = {}; // the scope variable exposed to map/reduce/finalize
  46. // o.jsMode = true; // default is false, force execution to stay in JS
  47. o.verbose = true; // default is false, provide stats on the job
  48. // o.out = {}; // objects to specify where output goes, by default is
  49. // returned, but can also be stored in a new collection
  50. // see: http://mongoosejs.com/docs/api.html#model_Model.mapReduce
  51. Person.mapReduce(o, function (err, results, stats) {
  52. console.log("map reduce took %d ms", stats.processtime);
  53. console.log(results);
  54. cleanup();
  55. });
  56. });
  57. });
  58. function cleanup() {
  59. Person.remove(function() {
  60. mongoose.disconnect();
  61. });
  62. }