Module: Mongoid::Contextual::Aggregable::Mongo
- Included in:
- Mongo
- Defined in:
- lib/mongoid/contextual/aggregable/mongo.rb
Overview
Contains behavior for aggregating values in Mongo.
Instance Method Summary collapse
-
#aggregates(field) ⇒ Hash
Get all the aggregate values for the provided field.
-
#avg(field) ⇒ Float
Get the average value of the provided field.
-
#max(field = nil) ⇒ Float, Document
Get the max value of the provided field.
-
#min(field = nil) ⇒ Float, Document
Get the min value of the provided field.
-
#sum(field = nil) ⇒ Float
Get the sum value of the provided field.
Instance Method Details
#aggregates(field) ⇒ Hash
Get all the aggregate values for the provided field.
27 28 29 30 31 32 33 34 |
# File 'lib/mongoid/contextual/aggregable/mongo.rb', line 27 def aggregates(field) result = collection.find.aggregate(pipeline(field), session: _session).to_a if result.empty? { "count" => 0, "sum" => nil, "avg" => nil, "min" => nil, "max" => nil } else result.first end end |
#avg(field) ⇒ Float
Get the average value of the provided field.
46 47 48 |
# File 'lib/mongoid/contextual/aggregable/mongo.rb', line 46 def avg(field) aggregates(field)["avg"] end |
#max(field = nil) ⇒ Float, Document
Get the max value of the provided field. If provided a block, will return the Document with the greatest value for the field, in accordance with Ruby’s enumerable API.
68 69 70 |
# File 'lib/mongoid/contextual/aggregable/mongo.rb', line 68 def max(field = nil) block_given? ? super() : aggregates(field)["max"] end |
#min(field = nil) ⇒ Float, Document
Get the min value of the provided field. If provided a block, will return the Document with the smallest value for the field, in accordance with Ruby’s enumerable API.
90 91 92 |
# File 'lib/mongoid/contextual/aggregable/mongo.rb', line 90 def min(field = nil) block_given? ? super() : aggregates(field)["min"] end |
#sum(field = nil) ⇒ Float
Get the sum value of the provided field. If provided a block, will return the sum in accordance with Ruby’s enumerable API.
108 109 110 |
# File 'lib/mongoid/contextual/aggregable/mongo.rb', line 108 def sum(field = nil) block_given? ? super() : aggregates(field)["sum"] || 0 end |