Tip : count is incorrect if used with limit in mongoid
Database : Mongodb
1.
campaigns = Campaign.all
campaigns.count
=> 211943
campaigns.count
=> 211943
2.
campaigns = Campaign.limit(1000)
campaigns.count
=> 211943
campaigns[1001]
=> nil
I was expecting count as 1000 for second query, but it came out to be same as first one. But actual objects stored in campaigns array are 1000 as it gives nil for 1001st index.
I spend quite some time while writing program to figure out this. I don’t have answer to this. This works correct if your database is mysql or postgres.
Someone may give answer to this and someone will save time in figuring it out.
In mongodb, count() ignores the effect of skip() and limit() methods by default. As a result, it counts the results in the entire query.
To consider the effect of skip() and limit() methods you can use “applySkipLimit ” option in your query.
For example:
campaigns = Campaign.limit(1000)
campaigns.count(applySkipLimit: true)
=> 1000
For more details refer this link:
https://docs.mongodb.com/manual/reference/method/cursor.count/#cursor.count