- Core MongoDB Operations (CRUD) >
- ObjectId
ObjectId¶
On this page
Overview¶
ObjectId is a 12-byte BSON type, constructed using:
- a 4-byte timestamp,
- a 3-byte machine identifier,
- a 2-byte process id, and
- a 3-byte counter, starting with a random value.
In MongoDB, documents stored in a collection require a unique
_id field that acts as a primary key. Because
ObjectIds are small, most likely unique, and fast to generate, MongoDB
uses ObjectIds as the default value for the _id
field if the
_id
field is not specified. MongoDB clients should add an _id
field with a unique ObjectId. However, if a client does not add an
_id
field, mongod
will add an _id
field that holds
an ObjectId.
Using ObjectIds for the _id
field provides the following
additional benefits:
- you can access the timestamp of the ObjectId’s creation, using the
getTimestamp()
method. - sorting on an
_id
field that storesObjectId
values is roughly equivalent to sorting by creation time, although this relationship is not strict withObjectId
values generated on multiple systems within a single second.
Also consider the BSON Documents section for related information on MongoDB’s document orientation.
ObjectId()¶
The mongo
shell provides the ObjectId()
wrapper class to
generate a new ObjectId, and to provide the following helper attribute
and methods:
str
The hexadecimal string value of the
ObjectId()
object.-
Returns the timestamp portion of the
ObjectId()
object as a Date. -
Returns the string representation of the
ObjectId()
object. The returned string literal has the format “ObjectId(...)
”.Changed in version 2.2: In previous versions
ObjectId.toString()
returns the value of the ObjectId as a hexadecimal string. -
Returns the value of the
ObjectId()
object as a hexadecimal string. The returned string is thestr
attribute.Changed in version 2.2: In previous versions
ObjectId.valueOf()
returns theObjectId()
object.
Examples¶
Consider the following uses ObjectId()
class in the
mongo
shell:
To generate a new ObjectId, use the
ObjectId()
constructor with no argument:In this example, the value of
x
would be:To generate a new ObjectId using the
ObjectId()
constructor with a unique hexadecimal string:In this example, the value of
y
would be:To return the timestamp of an
ObjectId()
object, use thegetTimestamp()
method as follows:This operation will return the following Date object:
Access the
str
attribute of anObjectId()
object, as follows:This operation will return the following hexadecimal string:
To return the string representation of an
ObjectId()
object, use thetoString()
method as follows:This operation will return the following output:
To return the value of an
ObjectId()
object as a hexadecimal string, use thevalueOf()
method as follows:This operation returns the following output: