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

118
Visualizações
mongo db query get documents befor and after

If I have the ObjectID of a document, how can I get the documents, that are before and after that document something like

db.getCollection('example').find({})
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Mongo's ObjectId is mostly monotonically increasing, on very rare occasions it's not like if you insert 2 documents at the exact same millisecond the "random" bit value added to it could technically break this. but this situation is very very rare.

So now you can query documents based this quality. for example this is how you'd fetch the x previous documents:

const id = ObjectId('xyz');
const documentsBefore = await db.getCollection('example').find(
    { _id: { $lt: id } })
    .sort({ _id: -1 }).limit(x).toArray();

Or documents after (he sort order and the query needs to change )

const id = ObjectId('xyz');
const documentsAfter = await db.getCollection('example').find(
    { _id: { $gt: id } })
    .sort({ _id: 1 }).limit(x).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