Module: MongoUtils::Aggregation::ClassMethods

Defined in:
lib/mongo_utils/aggregation.rb

Overview

The only requirement of the Aggregation module is that you have a class method defined on the including class called ‘collection`. Many of the popular ORMs provide this for you. Otherwise, you could do something like the following:

Examples:

class Person
  include MongoUtils::Aggregation

  def self.collection
    @db ||= Mongo::Connection.new.db('my_db')
    @collection ||= @db.collection('people')
  end
end

Instance Method Summary collapse

Instance Method Details

#group_by_created_at(interval = :month) ⇒ Array

Groups by the created_at date by the interval passed in

Parameters:

  • interval (Symbol) (defaults to: :month)

    valid values are :month, :day and :year

Returns:

  • (Array)

    returns an array of Hashes, containing the keys “count” and the grouping name



27
28
29
30
31
32
33
34
35
# File 'lib/mongo_utils/aggregation.rb', line 27

def group_by_created_at(interval = :month)
  interval = interval.to_s

  collection.group(
    :initial => {:count => 0},
    :keyf => "function(d) { return {#{interval}: d.created_at.get#{interval.capitalize}() + 1} }",
    :reduce => "function(doc, out) { out.count++; }"
  )
end