views:

680

answers:

1

Hey,

I have been using MongoDB and RoR to store logging data. I am pulling out the data and looking to page the results. Has anyone done paging with MongoDB or know of any resources online that might help get me started?

Cheers

Eef

+3  A: 

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.

Ryan Duffield
Thanks, That seems to do the job but now Ruby is complaining skip parameter has to be int, sigh, thanks for that :)
Eef