Cursor Pagination using ObjectID / Timestamp field in MongoDB

I sort and paginate records by a last_message_id field which takes an ObjectID (not timestamp), though both of them are the same if we deep dive.

The problem is some of the records may be ignored in pagination if we paginate using timestamp, because timestamps are not unique and they can be duplicate.

In my project there are two collections, Rooms and " Messages ". Whenever a user sends a message, The associated room of the message will be updated with the _id of the message. I do this because i want to show recently active rooms to users.

Is there a solution to the problem?

Take a look at the following: