Pagination with MongoDB Pagination with MongoDB mongodb mongodb

Pagination with MongoDB


Pagination in MongoDB can be accomplished by using a combination of limit() and skip().

For example, assume we have a collection called users in our active database.

>> db.users.find().limit(3)

This retrieves a list of the first three user documents for us. Note, this is essentially the same as writing:

>> db.users.find().skip(0).limit(3)

For the next three, we can do this:

>> db.users.find().skip(3).limit(3)

This skips over the first three user records, and gives us the next three. If there is only one more user in your database, don't worry; MongoDB is smart enough to only return data that is present, and won't crash.

This can be generalised like so, and would be roughly equivalent to what you would do in a web application. Assuming we have variables called PAGE_SIZE which is set to 3, and an arbitrary PAGE_NUMBER:

>> db.users.find().skip(PAGE_SIZE * (PAGE_NUMBER - 1)).limit(PAGE_SIZE)

I cannot speak directly as to how to employ this method in Ruby on Rails, but I suspect the Ruby MongoDB library exposes these methods.