Question

I need to run a collection on Mongoid but this collection does not have a model, so i cant use it like: Project.collection.map_reduce( ..., :query => scoped.selector) Does anyone know how could i do this? Thanks

Was it helpful?

Solution

Here's an answer/example that works for Mongoid 3.1.5 / Moped 1.5.1, hope that it helps. Please respond with your version info if you want something more specific to your environment. Note that since you don't have a Mongoid model, you loose the facilities of ODM level and have to drop down to the Moped driver level.

test/unit/session_test.rb

require 'test_helper'
require 'pp'

class SessionTest < ActiveSupport::TestCase
  def setup
    @session = Mongoid.default_session
    @collection_name = 'project'
    @collection = @session[@collection_name]
    @collection.drop
  end

  test "collection map-reduce without model" do
    puts "\nMongoid::VERSION:#{Mongoid::VERSION}\nMoped::VERSION:#{Moped::VERSION}"
    docs = [
        {'name' => 'Charlie', 'gender' => 'M', 'age' => 11},
        {'name' => 'Lucy', 'gender' => 'F', 'age' => 13},
        {'name' => 'Sally', 'gender' => 'F', 'age' => 15},
        {'name' => 'Linus', 'gender' => 'M', 'age' => 11},
        {'name' => 'Snoopy'},
    ]
    @collection.insert(docs)
    assert_equal docs.size, @collection.find.to_a.size
    pp @session.command(
           :mapReduce => @collection_name,
           :map =>  'function(){ emit(this.gender, this.age); }',
           :reduce =>  'function(key, values){ return Array.sum(values)/values.length; }',
           :out => { :inline => 1 },
           :query => { 'age' => { '$exists' => true } }
    )['results']
  end
end

$ rake test

Run options:

# Running tests:

[1/1] SessionTest#test_collection_map-reduce_without_model
Mongoid::VERSION:3.1.5
Moped::VERSION:1.5.1
[{"_id"=>"F", "value"=>14.0}, {"_id"=>"M", "value"=>11.0}]
Finished tests in 0.111151s, 8.9968 tests/s, 8.9968 assertions/s.
1 tests, 1 assertions, 0 failures, 0 errors, 0 skips
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top