Benjamin Harel
Benjamin Harel

Reputation: 2946

sum by more than one field in mongoid

Lets say

class User
  include Mongoid::Document

  field :sign_in_count,      :type => Integer, :default => 0
  field :some_other_count,   :type => Integer, :default => 0

end

I need to get a Hash that will consist of sum of both fields So the result will look like:

{ "sign_in_count" => 4, "some_other_count" => 12 } 

If I do

sign_in_sum = User.sum("sign_in_count")
some_other_sum = User.sum("some_other_count")

I see two mongo queries,but I need to do this in one. Please help.

Upvotes: 0

Views: 756

Answers (2)

Benjamin Harel
Benjamin Harel

Reputation: 2946

map = %Q{
   function() {
     emit( this.UserIdentifier, {
              num1: this.num1,
              num2: this.num2 } );
     }
   }

reduce = %Q{
  function(key, values) {
    var result = { num1: 0, num2: 0};
    values.forEach(function(value) {
      result.num1 += value.num1;
      result.num2 += value.num2;
    });
    return result;
  }
}

criteria = Data.where(:UserIdentifier => @user.id).map_reduce(map, reduce).out(replace: "mr-results")

Upvotes: 2

Deep Kapadia
Deep Kapadia

Reputation: 1458

Don't think of this as embedding JavaScript in Ruby but embedding a query in your application code. This is a fairly standard practice in many other languages/frameworks. Here is a post that may help:

http://kylebanker.com/blog/2009/12/mongodb-map-reduce-basics/

Upvotes: 1

Related Questions