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

115
Views
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 answers
Answer question

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