ObjectId

Small, likely unique, fast to generate, ordered identifier.

  • Small: Each ObjectId is 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 ObjectId may be as simple as querying the time and incrementing a counter.

  • Ordered: All ObjectId instances can be sorted by creating date, with a precision of one second. Two ObjectId instances 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 // 699dfad90ca573f85c0eec1c

Generating 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.

Constructors

Link copied to clipboard
constructor(timestamp: Instant, processId: Long, counter: Int)

Constructs a new ObjectId from its different components.

constructor(bytes: ByteArray)

Constructs a new ObjectId by reading a byte array.

constructor(hex: String)

Constructs a new ObjectId by reading a hexadecimal representation.

Types

Link copied to clipboard
object Companion
Link copied to clipboard

Default serializer for ObjectId.

Properties

Link copied to clipboard

Generates a byte representation of this ObjectId instance.

Link copied to clipboard

A 3-byte incrementing counter per client-side process, initialized to a random value. Always positive.

Link copied to clipboard
val hex: String

Generates a hex representation of this ObjectId instance.

Link copied to clipboard

5-byte random value generated per client-side process.

Link copied to clipboard

The ObjectId creation timestamp, with a resolution of one second.

Functions

Link copied to clipboard
operator fun compareTo(other: Instant): Int
open operator override fun compareTo(other: ObjectId): Int
Link copied to clipboard
open operator override fun equals(other: Any?): Boolean
Link copied to clipboard
open override fun hashCode(): Int
Link copied to clipboard
open override fun toString(): String