Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pagination with MongoDB

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

like image 534
RailsSon Avatar asked Jan 13 '10 11:01

RailsSon


People also ask

What is the use of the limit () and Skip () method?

The limit() function in MongoDB is used to specify the maximum number of results to be returned. Only one parameter is required for this function.to return the number of the desired result. Sometimes it is required to return a certain number of results after a certain number of documents. The skip() can do this job.

What is $Not in MongoDB?

$not performs a logical NOT operation on the specified <operator-expression> and selects the documents that do not match the <operator-expression> . This includes documents that do not contain the field .

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() is used when we required a certain number of results after a certain number of documents simultaneously we have use skip method in MongoDB. If we want to skip a certain number of documents from the collection, skip method will skip the specified documents that we have used with the MongoDB skip method.


1 Answers

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.

like image 113
Ryan Duffield Avatar answered Oct 16 '22 18:10

Ryan Duffield