Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

403
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda