Module: Mongoid::Contextual::Aggregable::Memory
Overview
Contains behavior for aggregating values in memory.
Instance Method Summary collapse
-
#aggregates(field) ⇒ Hash
Get all the aggregate values for the provided field.
-
#avg(field) ⇒ Numeric
Get the average value of the provided field.
-
#max(field = nil) ⇒ Numeric | Document
Get the max value of the provided field.
-
#min(field = nil) ⇒ Numeric | Document
Get the min value of the provided field.
-
#sum(field = nil) ⇒ Numeric
Get the sum value of the provided field.
Instance Method Details
#aggregates(field) ⇒ Hash
Get all the aggregate values for the provided field. Provided for interface consistency with Aggregable::Mongo.
20 21 22 23 24 |
# File 'lib/mongoid/contextual/aggregable/memory.rb', line 20 def aggregates(field) %w[count sum avg min max].each_with_object({}) do |method, hash| hash[method] = send(method, field) end end |
#avg(field) ⇒ Numeric
Get the average value of the provided field.
34 35 36 37 38 39 40 |
# File 'lib/mongoid/contextual/aggregable/memory.rb', line 34 def avg(field) total = count { |doc| !read_field_value(doc, field).nil? } return nil unless total > 0 total = total.to_f if total.is_a?(Integer) sum(field) / total end |
#max(field = nil) ⇒ Numeric | 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.
58 59 60 61 62 |
# File 'lib/mongoid/contextual/aggregable/memory.rb', line 58 def max(field = nil) return super() if block_given? aggregate_by(field, :max) end |
#min(field = nil) ⇒ Numeric | 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.
80 81 82 83 84 |
# File 'lib/mongoid/contextual/aggregable/memory.rb', line 80 def min(field = nil) return super() if block_given? aggregate_by(field, :min) end |
#sum(field = nil) ⇒ Numeric
Get the sum value of the provided field. If provided a block, will return the sum in accordance with Ruby's enumerable API.
99 100 101 102 103 |
# File 'lib/mongoid/contextual/aggregable/memory.rb', line 99 def sum(field = nil) return super(field || 0) if block_given? aggregate_by(field, :sum) || 0 end |