Mongo pagination Mongo pagination mongodb mongodb

Mongo pagination


Using morphia you can do this by the following command.

datastore.find(YourClass.class).field(id).smallerThan(lastId).limit(10).order("-ts");

Since you are querying for retrieving the items after the last retrieved id, you won't be bothered to deal with deleted items.


One thing I have thought up of is that you will have the same problem as with using skip() here unless you intend to change how your interface works.

Using ranged queries like this demands that you use a different kind of interface since it is must harder to detect now exactly what page you are on and how many pages exist in the future, especially if you are doing this to avoid problems with conventional paging.

The default type of interface to arise from this type of paging is merely a infinitely scrolling page, think of YouTube video comments or Facebook wall feed or even Google+. There is no physical pagination or "pages", instead you have a get more button.

This is the type of interface you will need to use to get ranged paging working better.

As for the query @cubbuk gives a good example:

datastore.find(YourClass.class).field(id).smallerThan(lastId).limit(10).order("-ts");

Except it should be greaterThan(lastId) since you want to find everything above that last _id. I would also sort by _id unless you make your OjbectIds sometime before you insert a record, if this is the case then you can use a specific timestamp set on insert instead.