Search code examples
mongodbspring-webfluxspring-data-mongodb

Reactive MongoDb objectId is long. But why indexing is so fast?


Reactive MongoDb's objectId is long.

A 4-byte timestamp, representing the ObjectId's creation, measured in seconds since the Unix epoch. A 5-byte random value generated once per process. This random value is unique to the machine and process. A 3-byte incrementing counter, initialized to a random value.

So if a document is created, I think Indexing time should be spent long time. but actually it isn't.

  1. But why _id indexing is so fast?
  2. if I set id value manually (ex random unique long value) when I create document, is indexing time will be long?

Solution

  • An ObjectID is 96 bits, right in the middle of a BIGINT which is 64 bits and often used for auto incrementing IDs in SQL databases and UUIDs which are 128 bits. They're not that big.

    ObjectID("507f1f77bcf86cd799439011") visually looks bigger than "4949320344", but if the latter was stored as a 128 bit number, it'd be bigger space-wise.

    One advantage that ObjectIDs have over UUID* is that by incorporating a timestamp, they will increase in value: newer IDs are larger than older IDs. That means that if you insert a document and then another one, it's not difficult to scan the index where it should be inserted. If you put random values into ObjectID() it will take longer to figure out where it belongs in the index.

    * UUIDv7 (as well as v6 and v8) solve this problem by being similar to ObjectIDs in that they start with an increasing timestamp, followed by random data. That makes them useful as primary keys. UUIDv1 contains a timestamp but does suffer from performance issues.