34

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"

Zahra
  • 6,798
  • 9
  • 51
  • 76

3 Answers3

41

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.

user10938362
  • 3,991
  • 2
  • 12
  • 29
zero323
  • 322,348
  • 103
  • 959
  • 935
  • 1
    Thanks for the reference. So turns out it is in ascending order on a wider time range but not in the orders smaller than a second. – Zahra Jun 25 '15 at 20:14
  • Well, I would be careful, in the worst case scenario "a wider time range" can be really wide. Consider scenario when you insert a document, set system clock to 1 January 1970 and insert another one. – zero323 Jun 25 '15 at 20:17
  • 1
    so...if the ObjectId is generated on one machine, then I can assume they are in an asc order? – Liu Wenzhe Aug 02 '18 at 02:25
9

For mongo version >= 3.4, the Objectid generation is changed a little. Its structs are:

  • a 4-byte value representing the seconds since the Unix epoch,
  • a 5-byte random value, and
  • a 3-byte counter, starting with a random value.

So the first 4 bytes are still the seconds since the Unix epoch, it is still almost ascending but not strictly.

https://docs.mongodb.com/manual/reference/bson-types/#objectid

chris
  • 2,761
  • 17
  • 24
8

_id: ObjectId(4 bytes timestamp, 3 bytes machine id, 2 bytes process id, 3 bytes incrementer)

This is the id structure. So only last 3 bytes will increment uniquely. So the answer of your question is yes.

zero323
  • 322,348
  • 103
  • 959
  • 935
  • 1
    so your answer is partially correct however with the consideration from the answer above it's almost ascending but not strictly since the timestamp bytes have a higher value and it could be out of order in a smaller than 1 second scales. – Zahra Jun 25 '15 at 20:19