In the last few months I have spent some time looking at the traffic stats for this blog and looks like this post is attracting a lot of visits, so this time I decided to write a couple of words about how to page query results from a MongoDB collection.

Let’s start from the very beginning, then! Here’s the code for connecting to the db:

at this point all you have to do is create a valid query (or just use {} to pick all the documents ), compute the number of items to skip and you’re almost done. Take a look at this gist:

As you may notice, paging is very similar to the normal Linq approach, using two methods, one for “skipping” the previous items ( details here ) and another for limiting the number of results to a fixed amount ( details here ).

A note on performance: skipping the items may become a very CPU intensive operation because the server has to scroll over all the items till the desired position. With large collections it is very important to plan your queries carefully and create your indexes accordingly.

As a bonus, the code shows also how to sort the items with an instance of IMongoSortBy and how to pick only a subset of the fields with IMongoFields, I guess I’ll post more on this in the next days.