icon-arrow icon-check icon-mail icon-phone icon-facebook icon-linkedin icon-youtube icon-twitter icon-cheveron icon-download icon-instagram play close close icon-arrow-uturn icon-calendar icon-clock icon-search icon-chevron-process icon-skills icon-knowledge icon-kite icon-education icon-languages icon-tools icon-experience icon-coffee-cup
Werken bij Integration & Application Talents
Blog 16/04/2018

The MongoDB ObjectId explained in under 2 minutes

Two minutes

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:

507f1f77bcf86cd799439011

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:

ObjectId("507c7f79bcf86cd7994f6c0e").getTimestamp()

returns
ISODate("2012-10-15T21:26:17Z")

Just as simple is extracting the stringvalue:

ObjectId.valueOf(("507c7f79bcf86cd7994f6c0e")
 returns 507c7f79bcf86cd7994f6c0e See the MongoDB reference for more examples.

 

Geen reacties

Geef jouw mening

Reactie plaatsen

Reactie toevoegen

Jouw e-mailadres wordt niet openbaar gemaakt.

Geen HTML

  • Geen HTML toegestaan.
  • Regels en alinea's worden automatisch gesplitst.
  • Web- en e-mailadressen worden automatisch naar links omgezet.

Wil je deel uitmaken van een groep gedreven en ambitieuze experts? Stuur ons jouw cv!