Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails mongoid中的多个字段求和_Ruby On Rails_Mongodb_Mongoid - Fatal编程技术网

Ruby on rails mongoid中的多个字段求和

Ruby on rails mongoid中的多个字段求和,ruby-on-rails,mongodb,mongoid,Ruby On Rails,Mongodb,Mongoid,比方说 class User include Mongoid::Document field :sign_in_count, :type => Integer, :default => 0 field :some_other_count, :type => Integer, :default => 0 end 我需要得到一个由两个字段的和组成的散列 因此,结果如下所示: { "sign_in_count" => 4, "some_ot

比方说

class User
  include Mongoid::Document

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

end
我需要得到一个由两个字段的和组成的散列 因此,结果如下所示:

{ "sign_in_count" => 4, "some_other_count" => 12 } 
如果我这样做

sign_in_sum = User.sum("sign_in_count")
some_other_sum = User.sum("some_other_count")
我看到了两个mongo查询,但我需要在一个查询中完成。
请提供帮助。

不要认为这是在Ruby中嵌入JavaScript,而是在应用程序代码中嵌入查询。这在许多其他语言/框架中都是相当标准的做法。 以下是一篇可能有帮助的帖子:


不要认为这是在Ruby中嵌入JavaScript,而是在应用程序代码中嵌入查询。这在许多其他语言/框架中都是相当标准的做法。 以下是一篇可能有帮助的帖子:


MapReduce可以帮上忙。你是说在Ruby代码中嵌入JS代码?MapReduce可以帮上忙。你是说在Ruby代码中嵌入JS代码?
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")