Tag Archives: mongodb

map-reduce using mongoid

It took me a while to work out how to use map-reduce in Ruby using mongoid so I thought I’d share it here in-case it helps anyone else get there quicker. I start out with a model that includes Mongoid::Document:

To map-reduce across the collection I need to define a map and reduce function in javascript then run the on the collection:

I can roll this into my VisitorSession model:

This obviously makes it easier to call:

>> VisitorSession.first(:conditions => {:project_id => '2f5178'}).visits_for_project
=> 1

Tagged ,