RoR Tips & Tricks Series – #2

Tip : count is incorrect if used with limit in mongoid

Database : Mongodb

campaigns = Campaign.all
=> 211943

campaigns = Campaign.limit(1000)
=> 211943

=> 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.

This entry was posted in General. Bookmark the permalink.

1 Response to RoR Tips & Tricks Series – #2

  1. anujverma10 says:

    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:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s