Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

405
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda