Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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"

like image 253
Zahra Avatar asked Jun 25 '15 18:06

Zahra


People also ask

Is MongoDB ObjectId incremental?

MongoDB does not have out-of-the-box auto-increment functionality, like SQL databases. By default, it uses the 12-byte ObjectId for the _id field as the primary key to uniquely identify the documents.

How is MongoDB _id generated?

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field. The 5 byte "random value" does not appear to be random.

How is ObjectId generated?

ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes. ObjectID encodes the timestamp of its creation time, which may be used for queries or to sort by creation time.

Is MongoDB ObjectId unique across collections?

The uniqueness constraint for _id is per collection, so yes - one and the same ID can occur once per Collection. It's however very unlikely, if not impossible, for the same ID to be generated twice.


2 Answers

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.

like image 81
zero323 Avatar answered Sep 20 '22 15:09

zero323


_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.

like image 20
suleman ravla Avatar answered Sep 19 '22 15:09

suleman ravla