Collection ID length in MongoDB

ashish bandiwar picture ashish bandiwar · Aug 18, 2014 · Viewed 19k times · Source

i am new to mongodb and stack overflow.

I want to know why on mongodb collection ID is of 24 hex characters? what is importance of that?

Answer

Stennie picture Stennie · Aug 21, 2014

Why is the default _id a 24 character hex string?

The default unique identifier generated as the primary key (_id) for a MongoDB document is an ObjectId. This is a 12 byte binary value which is often represented as a 24 character hex string, and one of the standard field types supported by the MongoDB BSON specification.

The 12 bytes of an ObjectId are constructed using:

  • a 4 byte value representing the seconds since the Unix epoch
  • a 3 byte machine identifier
  • a 2 byte process id
  • a 3 byte counter (starting with a random value)

What is the importance of an ObjectId?

ObjectIds (or similar identifiers generated according to a GUID formula) allow unique identifiers to be independently generated in a distributed system.

The ability to independently generate a unique ID becomes very important as you scale up to multiple application servers (or perhaps multiple database nodes in a sharded cluster). You do not want to have a central coordination bottleneck like a sequence counter (eg. as you might have for an auto-incrementing primary key), and you will want to insert new documents without risk that a new identifier will turn out to be a duplicate.

An ObjectId is typically generated by your MongoDB client driver, but can also be generated on the MongoDB server if your client driver or application code or haven't already added an _id field.

Do I have to use the default ObjectId?

No. If you have a more suitable unique identifier to use, you can always provide your own value for _id. This can either be a single value or a composite value using multiple fields.

The main constraints on _id values are that they have to be unique for a collection and you cannot update or remove the _id for an existing document.