Ram Viswanathan
Ram Viswanathan

Reputation: 201

mongo sorting with pagination

I have a need to implement paging in my mongodb collection. This is an example of a document in my collection

{
  "_id" : "<Mongo Generated>",
  "category" : "abc",
  "createdDate" : "<Date of creation of the document>",
  "markedDate" : "<Date when the document is marked 
               (marking is an activity that is done via my application>"
}

This is my requirement:

  1. I need to retrieve all documents in category "abc", however in pages of 10 documents per page
  2. The paging should be done only after the documents are sorted - I have to sort the documents by markedDate (Descending) first, then createdDate (descending)
  3. A limit of 10 results should be applied
  4. I should be able to skip to any page based on the page number that comes in the input

I tried to execute the following query to sort results using aggregate:

db.getCollection('testcollection').aggregate(
   {$match:{"category" : "abc"}}, 
   {$sort:{markedDate: -1, createdDate : -1}
})

However, how do I page? I can use a skip + limit option, however I went through some posts before posting this question, and it is not recommended for large data sets. I am anticipating that my collection with have around 75000 documents.

Also, since my date is stored in ISO date format, I see that the visibility is only at the level of seconds. I may have 2 documents created at the same second.

What's the best way to page my results without causing a performance impact?

Please advise.

Upvotes: 2

Views: 3431

Answers (1)

Mukesh Yadav
Mukesh Yadav

Reputation: 2386

How about using sort function directly

db.testcollection.find({}).sort({createdDate:-1}).skip(1).limit(10)

Upvotes: 2

Related Questions