Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Range based paging mongodb

on the mongodb docs it says: (source)

Unfortunately skip can be (very) costly and requires the server to walk from the beginning of the collection, or index, to get to the offset/skip position before it can start returning the page of data (limit). As the page number increases skip will become slower and more cpu intensive, and possibly IO bound, with larger collections. Range based paging provides better use of indexes but does not allow you to easily jump to a specific page.

What is range based paging and where is the documentation for it?

like image 324
Harry Avatar asked Jul 24 '11 09:07

Harry


People also ask

What is skip and limit in pagination?

MongoDB has an extremely straightforward way to implement pagination: using skip and limit operations on a cursor. skip(n) skips n items in a query, while limit(m) returns only the next m items starting from the n-th one.

What is keyset pagination?

Keyset pagination (also known as the "seek method") is used to fetch a subset of records from a table quickly. It does this by restricting the set of records returned with a combination of WHERE and LIMIT clauses.

What is Skip method in MongoDB?

MongoDB – skip() Method In MongoDB, the skip() method will skip the first n document from the query result, you just need to pass the number of records/documents to be skipped.


1 Answers

The basic idea is to write the paging into the query predicate pattern.

For example if you list forum posts by date and you want to show the next page then use the date of the last post on the current page as a predicate. MongoDB can use the index built on the date field.

//older posts
db.forum_posts.find({date: {$lt: ..last_post_date..} }).sort({date: -1}).limit(20);

Of course this gets a little more complicated if the field you are using for sorting is not unique.

like image 63
Karoly Horvath Avatar answered Sep 26 '22 01:09

Karoly Horvath