module Mongoid::Contextual::Aggregable::Mongo
def aggregates(field)
-
(Hash)- A Hash containing the aggregate values.
Parameters:
-
field(String, Symbol) -- The field name.
Other tags:
- Example: Get all the aggregate values. -
def aggregates(field) result = collection.find.aggregate(pipeline(field), session: _session).to_a if result.empty? if Mongoid.broken_aggregables { "count" => 0, "sum" => nil, "avg" => nil, "min" => nil, "max" => nil } else Aggregable::EMPTY_RESULT.dup end else result.first end end
def avg(field)
-
(Float)- The average.
Parameters:
-
field(Symbol) -- The field to average.
Other tags:
- Example: Get the average of a single field. -
def avg(field) aggregates(field)["avg"] end
def max(field = nil)
-
(Float, Document)- The max value or document with the max
Parameters:
-
field(Symbol) -- The field to max.
Other tags:
- Example: Get the document with the max value. -
Example: Get the max of a single field. -
def max(field = nil) block_given? ? super() : aggregates(field)["max"] end
def min(field = nil)
-
(Float, Document)- The min value or document with the min
Parameters:
-
field(Symbol) -- The field to min.
Other tags:
- Example: Get the document with the min value. -
Example: Get the min of a single field. -
def min(field = nil) block_given? ? super() : aggregates(field)["min"] end
def pipeline(field)
-
(Array)- The array of pipeline operators.
Parameters:
-
field(String, Symbol) -- The name of the field.
Other tags:
- Example: Get the pipeline. -
Other tags:
- Api: - private
def pipeline(field) db_field = "$#{database_field_name(field)}" sort, skip, limit = criteria.options.values_at(:sort, :skip, :limit) pipeline = [] pipeline << { "$match" => criteria.exists(field => true).selector } pipeline << { "$sort" => sort } if sort && (skip || limit) pipeline << { "$skip" => skip } if skip pipeline << { "$limit" => limit } if limit pipeline << { "$group" => { "_id" => field.to_s, "count" => { "$sum" => 1 }, "max" => { "$max" => db_field }, "min" => { "$min" => db_field }, "sum" => { "$sum" => db_field }, "avg" => { "$avg" => db_field } } } end
def sum(field = nil)
-
(Float)- The sum value.
Parameters:
-
field(Symbol) -- The field to sum.
Other tags:
- Example: Get the sum for the provided block. -
Example: Get the sum of a single field. -
def sum(field = nil) block_given? ? super() : aggregates(field)["sum"] || 0 end