Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

404
Views
Paginate Mongoose / MongoDB query: sort by two fields starting from a point

I want to sort a collection by the rating field and the _id field, both descending { $sort: { rating:-1 }, { _id:-1 } }. Since I'm using $limit I want to be able to do another request to get the following objects. I tried doing it with a $match like this { rating: {$lte: lastRating}, _id : { $lt: lastID} }, where lastRating and lastID are the previous values of the last item in the last returned array But that doesn't return anything.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

What you are describing is called pagination.

How to implement this pattern is already described in depth by many others (like this). leaving this here for others

The reason your query does not return any documents on the next page, however, is probably simple because the tiebreaker is implemented incorrectly (I am assuming you are using the _id as tiebreaker).

It should look similar to this:

// page 1
collection
  .find({})
  .sort({ rating: -1, _id: -1 })
  .limit(limit)
  .toArray();
// page n
collection
  .find({
    $and: [
      { ...any actual query here },
      // this is the pagination query
      {
        $or: [
          { rating: { $lt: lastRating } },
          {
            rating: lastRating,
            _id: { $lt: ObjectId(lastID) } 
        ]
    ]
  })
  .sort({ rating: -1, _id: -1 })
  .limit(limit)
  .toArray();
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!