在没有模型的mongoid上使用集合

时间:2013-06-10 18:46:37

标签: mongodb collections map mongoid reduce

我需要在Mongoid上运行一个集合,但是这个集合没有模型,所以我不能像以下那样使用它:Project.collection.map_reduce( ..., :query => scoped.selector) 有谁知道我怎么能这样做? 感谢

1 个答案:

答案 0 :(得分:1)

这是一个适用于Mongoid 3.1.5 / Moped 1.5.1的答案/示例,希望它有所帮助。 如果您想要更具体的环境,请回复您的版本信息。 请注意,由于您没有Mongoid模型, 你失去了ODM级别的设施,必须下降到Moped驱动程序级别。

测试/单元/ 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