0

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

4

1 回答 1

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

$耙子测试

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
于 2013-11-03T20:56:13.613 回答