Mongoid 3 - access map_reduce results

2019-05-23 07:06发布

问题:

In mongoid 2, this used to work:

mr_collection = self.collection.map_reduce(map, reduce, {
  :query => query,
  :finalize => finalize,
  :out => {:replace => 'mr_results'}
})

limit = (options[:limit] || 10)
skip = (options[:skip].to_i || nil)
page = if skip >= limit
  ((skip+limit) / limit)
else
  1
end

sort = if options[:sort_by_vintage]
  [['value.vy', :desc], ['value.s', (options[:sort] || :desc)], ['value.pml', :asc]]
elsif options[:sort_by_sDate]
  [['value.sDate', :desc], ['value.s', (options[:sort] || :desc)], ['value.pml', :asc]]
else
  [['value.s', (options[:sort] || :desc)], ['value.pml', :asc]]
end
paginator = WillPaginate::Collection.new(page, limit, collection_count)
collection = mr_collection.find({},{
    :sort => sort,
    :limit => limit,
    :skip => skip
  }
).to_a

I have updated the map_reduce call to be:

mr_collection = self.where(query).map_reduce(map, reduce).finalize(finalize).out({:replace => 'mr_results'})

Which does not produce any errors any more, but the collection = mr_collection.find.... always fails no matter what I try. Here are a few attempts:

(rdb:1) mr_collection.find.sort(sort)

which produces .rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/debug.rb:130:in `eval':wrong number of arguments(1 for 0)

I can see that (rdb:1) mr_collection.class Mongoid::Contextual::MapReduce

(rdb:1) mr_collection.find.class
Enumerator

Trying: (rdb:1) mr_collection.sort(sort) .rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/debug.rb:130:in `eval':wrong number of arguments(1 for 0) so same error

Thanks for your help

UPDATE

Fixed it by using:

collection = mr_collection.find(
    :sort => sort,
    :limit => limit,
    :skip => skip
 )

My problem is now using collection.to_a, which I know works well for regular hashes, but the results in the collection are of type Moped::BSON::Document. Calling any Enumerator method on collection, results in this error:

undefined method `call' for #<Hash:

I'm going mad. Please help!!

So of the things I tried include:

collection = collection.each {|c| c.to_hash}.to_a

and

collection = collection.collect {|c| c.to_hash}.to_a

Thanks :)

回答1:

Finally figured it out thanks to the Mongoid google group. Details here: https://groups.google.com/d/topic/mongoid/T6XhqLtofTE/discussion

The one liner fix is:

collection = mr_collection.send(:documents).sort(sort).limit(limit).skip(skip).to_a

In an upcoming version of mongoid, Mongoid::Contextual::MapReduce#documents will be changed from a private method to a public one, and the .send(:documents) won't be needed anymore.