ObjectId
Small, likely unique, fast to generate, ordered identifier.
Small: Each
ObjectIdis 12 bytes long, shorter than a UUID's 16 bytes.Likely unique: Each driver randomly selects a generation range, so conflicts are unlikely.
Fast to generate: Depending on the generation strategy, generating a new
ObjectIdmay be as simple as querying the time and incrementing a counter.Ordered: All
ObjectIdinstances can be sorted by creating date, with a precision of one second. TwoObjectIdinstances created by the same driver are sorted with even more precision.
Composition
An ObjectId is composed of:
A 4-byte timestamp, representing the
ObjectId's creation date, with a precision of one second,A 5-byte random processId, unique to each machine and process, to decrease conflicts,
A 3-byte incrementing counter, initialized at a random value.
ObjectId instances are generally represented as 24-characters hexadecimal strings:
ObjectId("699dfad90ca573f85c0eec1c").hex // 699dfad90ca573f85c0eec1cGenerating new ObjectIds
There are different strategies to generate new ObjectId instances; they are encoded by the ObjectIdGenerator interface.
The ObjectIdGenerator used by each driver is available directly on each collection:
users.insert(
User(
_id = users.newId(), // Generate an ObjectId using the configuration specific to that collection
name = "Bob",
)
)External resources
Thread safety
Instances of this class are immutable and thread-safe.