- Whitehorses - http://blog.whitehorses.nl -

The MongoDB ObjectId explained in under 2 minutes

Tweet [1]

As you may have noticed, especially when your background is from a MySQL or Oracle database, is that the unique identifier for database records (or ‘documents’ in MongoDB) is quite different. It’s not a incremental counter, but a long string of characters. 12 bytes in hexadecimal format, to be precise. And although they appear to contain no information, they actually do. This is how an ObjectId is composed.

Let’s take an ObjectId:


The first part is a 4-byte value representing the seconds since the Unix epoch (hence, it’s a timestamp!), the next part is a 3-byte machine identifier unique for every machine, then a 2-byte containing the process id, and finally a 3-byte counter, starting with a random value.

This combination of values (timestamp, machine, process, counter) guarantees a unique value for the ObjectId.

Because the timestamp is included, it’s possible to extract it from the Id. That’s fairly simple, because Mongo provides a function for that:



Just as simple is extracting the stringvalue:

 returns 507c7f79bcf86cd7994f6c0e See the MongoDB reference [2] for more examples.