ruby on rails - Sum mongoid specified field -
def self.group_by(field, format = 'day') key_op = [['year', '$year'], ['month', '$month'], ['day', '$dayofmonth']] key_op = key_op.take(1 + key_op.find_index { |key, op| format == key }) project_date_fields = hash[*key_op.collect { |key, op| [key, {op => "$#{field}"}] }.flatten] group_id_fields = hash[*key_op.collect { |key, op| [key, "$#{key}"] }.flatten] pipeline = [ {"$project" => {"name" => 1, field => 1}.merge(project_date_fields)}, {"$group" => {"_id" => group_id_fields, "count" => {"$sum" => "$qtyused"}}}, {"$sort" => {"count" => -1}} ] collection.aggregate(pipeline)<br> end
when execute script, count result 0.
how can sum attributes qtyused?
you not projecting "qtyused" field
pipeline = [ {"$project" => {"name" => 1, field => 1, "qtyused' => 1}.merge(project_date_fields)}, {"$group" => {"_id" => group_id_fields, "count" => {"$sum" => "$qtyused"}}}, {"$sort" => {"count" => -1}} ]
Comments
Post a Comment