Find all records after particular record

Hello! I want to do something simple. I have a collection of chat messages and I want to return them in groups of 100. I want to be able to get the next 100 messages after a message with a given _id.

One way to do this would be to query for that particular record, get the timestamp, then query for the next 100 records with an earlier timestamp. Or the client itself could just send the timestamp of the relevant message directly to the server, so only one query would need to be made.

However, I am wonder if it is possible to do what I am trying to do in a single query, given the _id of the relevant message?

The answer depends - what’s the value of the _id field? Is it the default ObjectId() generated by the client (or server)?


Hi Asya,

I have the same question regarding to get records after any specific one.
and I’m using the mongodb generated value in the _id “objectId”.

The default _id value is an ObjectId which encodes the timestamp as its first four bytes so it can be used as equivalent to inserted on date field. In other words, you can sort by it, and ensure a stable sort where highest (or lowest) value in one batch can be used to ensure the next batch started after that value.