MongoDB - Mongoid map reduce basic operation MongoDB - Mongoid map reduce basic operation mongodb mongodb

MongoDB - Mongoid map reduce basic operation


Taking the examples from http://mongoid.org/en/mongoid/docs/querying.html#map_reduce and adapting them to your situation and adding comments to explain.

map = %Q{  function() {    emit(this.sdate, { age: this.age, name : this. name });       // here "this" is the record that map      // is going to be executed on  }  }reduce = %Q{  function(key, values) {              // this will be executed for every group that           // has the same sdate value    var result = { avg_of_ages: 0 };    var sum = 0;    // sum of all ages    var totalnum = 0  // total number of people    values.forEach(function(value) {      sum += value.age;        });    result.avg_of_ages = sum/total   // finding the average    return result;  }}results = Person.map_reduce(map, reduce) //You can access this as an array of mapsfirst_average = results[0].avg_of_agesresults.each do |result|   // do whatever you want with resultend

Though i would suggest you use Aggregation and not map reduce for such a simple operation. The way to do this is as follows :

 results = Person.collection.aggregate([{"$group" => { "_id" => {"sdate" => "$sdate"},                                                 "avg_of_ages"=> {"$avg" : "$age"}}}])

and the result will be almost identical with map reduced and you would have written a lot less code.