Class: Mongoid::MapReduce::Formula::ArrayValues
- Inherits:
-
Object
- Object
- Mongoid::MapReduce::Formula::ArrayValues
- Includes:
- Serialization
- Defined in:
- lib/mongoid/mapreduce/formula/array_values.rb
Instance Method Summary collapse
-
#initialize(fields, options = {}) ⇒ ArrayValues
constructor
A new instance of ArrayValues.
-
#map ⇒ Object
Generate a map function Emits the value 1 for each value of the given array field.
-
#process(collection) ⇒ Object
Process the results of a given collection.
-
#reduce ⇒ Object
Generates a reduce function Adds the given values.
Methods included from Serialization
Constructor Details
#initialize(fields, options = {}) ⇒ ArrayValues
Returns a new instance of ArrayValues.
10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/mongoid/mapreduce/formula/array_values.rb', line 10 def initialize(fields, ={}) [:map_key] ||= :_id [:count_type] ||= Integer [:count_field] ||= :_count if fields.any? raise "Error: The Array Values formula does not take any fields. Please see documentation." end @field_name = [:map_key] @field_type = [:count_type] @count_field = [:count_field] end |
Instance Method Details
#map ⇒ Object
Generate a map function Emits the value 1 for each value of the given array field
Returns String
28 29 30 31 32 33 34 |
# File 'lib/mongoid/mapreduce/formula/array_values.rb', line 28 def map fn = "function() { " fn << "this.#{@field_name.to_s}.forEach(function(value) { " fn << "emit(value, 1); " fn << "}); " fn << "}" end |
#process(collection) ⇒ Object
Process the results of a given collection
collection - the MongoDB collection returned from the map/reduce op
Returns Results
53 54 55 56 57 58 59 |
# File 'lib/mongoid/mapreduce/formula/array_values.rb', line 53 def process(collection) return collection.inject(Results.new) do |h, k| key = k.values[0].to_s =~ /(^[-+]?[0-9]+$)|(\.0+)$/ ? Integer(k.values[0]) : Float(k.values[0]) val = serialize(k.values[1].is_a?(String) ? k.values[1].split(',') : k.values[1], @field_type) h << Document.new(:_key_name => @field_name, :_key_value => key, key.to_s => val, @count_field => val) end end |
#reduce ⇒ Object
Generates a reduce function Adds the given values
Returns String
40 41 42 43 44 45 46 |
# File 'lib/mongoid/mapreduce/formula/array_values.rb', line 40 def reduce fn = "function(k, v) { " fn << "var result = 0; " fn << "v.forEach(function(val) { result += val; }); " fn << "return result; " fn << "}" end |