Reputation: 325
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?
Upvotes: 1
Views: 705
Reputation: 6068
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
.
Upvotes: 2
Reputation: 8055
have you tried
Foo.where(color: 'red').pluck(:id)
might be faster (not sure)
Upvotes: 1