Iván Cortés Romero Iván Cortés Romero - 7 months ago 54
Ruby Question

Mongoid::Criteria to array in Ruby

I have a

which has 634 results:

selector: {"search_id"=>155, "posted_time"=>{"$gte"=>2016-05-31 15:43:40 UTC, "$lte"=>2016-06-07 15:43:40 UTC}}
options: {:sort=>{"posted_time"=>-1}, :limit=>200}
class: MongoPost
embedded: false>

=> 634

=> 200

This is a problem, because when I map the object, the result is not which I expected:

data.map{|element| element.type}.count
=> 200

What is doing on, and how can I resolve it?


Your criteria has limit: 200 on it. each (and, by extension, map) respects the limit. That's why you get 200 records.

Why count ignores limit - this is a good question. I don't know exactly, but I suspect it has something to do with pagination. That is, having one criteria object, you can fetch a page and know total number of matching records (from which you can infer total number of pages).

To get count of limited query you can do something like:


This count is not the one from Mongoid, it's from Enumerable and will respect the limit.

About unsetting the limit: quick googling didn't reveal a suitable api, but you can always override limit with a bigger value. This, perhaps:

criteria.limit(criteria.count).to_a # get all records, without limit