简体   繁体   中英

Ruby map/collect is slow on a large Mongoid collection

I have a Mongoid collection on which I run a where query.

Now, I would like to build an array containing a values of a specific field from all the documents in the collection.

eg if my Monogid model is

class Foo
    field :color, type: String
end

I'd like to do something like this -

red_ducks = Foo.where(color: 'red')
red_duck_ids = red_ducks.map(&:_id)

Unfortunately, when the result of the query is large it takes a long time. It takes 6 seconds for 10,000 documents in my case, for example.

Is there any way to speed this up?

Can't you just call distinct on your scope with _id as an attribute?

red_duck_ids = Foo.where(color: 'red').distinct(:_id)

Which will return you a list of all _id s that meet your conditions. You can find more information on Mongo's distinct documentation .

You can also have a look at only and if you are using version 3.1 or newer you can also use Criteria#pluck .

have you tried

Foo.where(color: 'red').pluck(:id)

might be faster (not sure)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM