MongoDB - paging

Roger Johansson picture Roger Johansson · Feb 19, 2011 · Viewed 56k times · Source

When using MongoDB, are there any special patterns for making e.g. a paged view? say a blog that lists the 10 latest posts where you can navigate backwards to older posts.

Or do one solve it with an index on e.g. blogpost.publishdate and just skip and limit the result?

Answer

Scott Hernandez picture Scott Hernandez · Feb 19, 2011

Using skip+limit is not a good way to do paging when performance is an issue, or with large collections; it will get slower and slower as you increase the page number. Using skip requires the server to walk though all the documents (or index values) from 0 to the offset (skip) value.

It is much better to use a range query (+ limit) where you pass in the last page's range value. For example if you are sorting by "publishdate" you would simple pass the last "publishdate" value as the criteria for the query to get the next page of data.