Вопрос

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.

e.g. 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 _ids 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)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top