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

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

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 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