BSON Types — MongoDB Manual https://docs.mongodb.com/manual/reference/bson-types/#objectid
ObjectId
ObjectIds are small, likely unique, fast to generate, and ordered. ObjectId values consist of 12 bytes, where the first four bytes are a timestamp that reflect the ObjectId’s creation. Specifically:
- a 4-byte value representing the seconds since the Unix epoch,
- a 5-byte random value, and
- a 3-byte counter, starting with a random value.
In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id
field, the MongoDB driver automatically generates an ObjectId for the _id
field.
This also applies to documents inserted through update operations with upsert: true.
MongoDB clients should add an _id
field with a unique ObjectId. Using ObjectIds for the _id
field provides the following additional benefits:
-
in the
mongo
shell, you can access the creation time of theObjectId
, using theObjectId.getTimestamp()
method. -
sorting on an
_id
field that storesObjectId
values is roughly equivalent to sorting by creation time.IMPORTANT
While ObjectId values should increase over time, they are not necessarily monotonic. This is because they:
- Only contain one second of temporal resolution, so ObjectId values created within the same second do not have a guaranteed ordering, and
- Are generated by clients, which may have differing system clocks.