Quick Tip : Pagination in MongoDB using Scala


Here is the example of how you can do Pagination or Paging in MongoDB using Scala.

 
  /*
 * Pagination For messages
 */

  def getAllMessages(pageNumber: Int, messagesPerPage: Int): List[Message] = {

    val messsagesRetrieved = MessageDAO.find(MongoDBObject()).                     
    skip((pageNumber - 1) * messagesPerPage).limit(messagesPerPage).toList      
    messsagesRetrieved

  }

Note :-

1. pageNumber : Page No. like 1st Page , 2nd Page and so on.
2. messagesPerPage : No of messages to be displayed on each page.
3. Here the find method we’ve used is of SalatDAO. You can use your own find method.

About Neelkanth Sachdeva

Project Manager @ eCIFM Solutions Inc. Previous : Senior Software Engineer @ Evernym Inc. Previous : Software Consultant @ Knoldus Software LLP Software Consultant @ Inphina Technologies
This entry was posted in Web. Bookmark the permalink.

2 Responses to Quick Tip : Pagination in MongoDB using Scala

  1. Great post, however you typically never want to “skip” in mongodb; as it has to run through the entire index the further “the skip” you go. Take the last object ID and use that as the offset I.e. (_id $lte Y) + limit(X)

  2. Great post, however you typically never want to \”skip\” in mongodb; as it has to run through the entire index the further \”the skip\” you go. Take the last object ID and use that as the offset I.e. (_id $lte Y) + limit(X)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s