Method: Mongoid::Contextual::Aggregable::Memory#sum

Defined in:
lib/mongoid/contextual/aggregable/memory.rb

#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.

Examples:

Get the sum of a single field.

aggregable.sum(:likes)

Get the sum for the provided block.

aggregable.sum(&:likes)

Parameters:

  • field (Symbol | Numeric) (defaults to: nil)

    The field to sum, or the initial value of the sum when a block is given.

Returns:

  • (Numeric)

    The sum value.



97
98
99
100
101
# File 'lib/mongoid/contextual/aggregable/memory.rb', line 97

def sum(field = nil)
  return super(field || 0) if block_given?

  aggregate_by(field, :sum) || 0
end