Skip to content

Instantly share code, notes, and snippets.

@zargony
Created July 26, 2010 18:05
Show Gist options
  • Save zargony/490948 to your computer and use it in GitHub Desktop.
Save zargony/490948 to your computer and use it in GitHub Desktop.
module MongoidUtils
# Utility module to include in Mogoid documents
module Document
extend ActiveSupport::Concern
module ClassMethods
# Do a map/reduce operation on the document's collection and return the results as one big
# hash. If a block is given, it is yielded with key and value for every result instead
# (this comes in handy if you expect large results)
def map_reduce (map_function, reduce_function, options = {})
options[:query] = criteria.selector
tmp_collection = criteria.klass.collection.map_reduce(map_function, reduce_function, options)
if block_given?
tmp_collection.find.each { |doc| yield doc['_id'], doc['value'] }
nil
else
tmp_collection.find.to_a.inject({}) { |results, doc| results[doc['_id']] = doc['value']; results }
end
ensure
tmp_collection.drop if tmp_collection
end
alias :mapreduce :map_reduce
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment