Module: Mongoid::Contextual::Aggregable::MongoEx::ClassMethods
- Defined in:
- lib/mongoid/contextual/aggregable/mongo_ex.rb
Instance Method Summary collapse
-
#aggregates(field = nil) ⇒ 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 = nil) ⇒ Hash
Get all the aggregate values for the provided field.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/mongoid/contextual/aggregable/mongo_ex.rb', line 30 def aggregates(field = nil) if (field.present?) if query.count > 0 result = collection.aggregate(pipeline(field)).to_a if result.empty? {"count" => query.count, "avg" => 0, "sum" => 0} else result.first end else {"count" => 0} end else Aggregates.new(self) end end |
#avg(field) ⇒ Float
Get the average value of the provided field.
57 58 59 |
# File 'lib/mongoid/contextual/aggregable/mongo_ex.rb', line 57 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.
79 80 81 |
# File 'lib/mongoid/contextual/aggregable/mongo_ex.rb', line 79 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.
101 102 103 |
# File 'lib/mongoid/contextual/aggregable/mongo_ex.rb', line 101 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.
119 120 121 |
# File 'lib/mongoid/contextual/aggregable/mongo_ex.rb', line 119 def sum(field = nil) block_given? ? super() : aggregates(field)["sum"] || 0 end |