Is MongoDB _id (ObjectId) generated in an ascending order?

Zahra picture Zahra · Jun 25, 2015 · Viewed 10k times · Source

I know how the _id column contains a representation of timestamp when the document has been inserted into the collection. here is an online utility to convert it to timestamp: http://steveridout.github.io/mongo-object-time/

What I'm wondering is if the object id string itself is guaranteed maintain the ascending order or not? i.e. does this comparison always return true?

"newest object id" > "second newest object id"

Answer

zero323 picture zero323 · Jun 25, 2015

No, there is no guarantee whatsoever. From the official documentation (at the time of the original answer):

The relationship between the order of ObjectId values and generation time is not strict within a single second. If multiple systems, or multiple processes or threads on a single system generate values, within a single second; ObjectId values do not represent a strict insertion order. Clock skew between clients can also result in non-strict ordering even for values, because client drivers generate ObjectId values, not the mongod process.

And from the latest docs

While ObjectId values should increase over time, they are not necessarily monotonic. This is because they:

Only contain one second of temporal resolution, so ObjectId values created within the same second do not have a guaranteed ordering, and Are generated by clients, which may have differing system clocks.