mongo db query get documents befor and after

Viewed 112

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({})
1 Answers

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();
Related