ObjectId and _id

_id with ObjectId

An _id field in MongoDB is like a primary key in an RDBMS that is created by default in any insert if not specified in the document and it's used to identify and make each document unique. An _id field by default contains an ObjectId. The ObjectId contains the following specifications:

  • Unique: Two different documents can not have the same ObjectId
  • Immutable: An ObjectId can not be edited after insertion
  • Bson datatype
  • 12 byte value:
    • 4 bytes: timestamp value, representing the ObjectId’s creation, measured in seconds since the Unix epoch
    • 5 bytes: random value
    • 3 bytes: incrementing counter, initialized to a random value

_id and ObjectId example

Let's try to insert some dummy data into our database.

Auto generating the _id field with an ObjectId

{ name: "ObjectId" }

The result of creation will contains an additional field named _id that contains as value an ObjectId.

{ "_id" : ObjectId("5e43e017dfa432477f122816"), "name" : "ObjectId" }

Implicitly defining the _id field

The value "my-id" should be unique and does need to be a string, it can be in any bson type.

{_id: "my-id" name: "ObjectId" }

Creating new ObjectId

Generate a New ObjectId

To generate a new ObjectId, use ObjectId() with no argument:

x = ObjectId()

In this example, the value of x would be:


timestamp portion of the object as a Date.

To do so we use the getTimestamp method on an ObjectId because the first 4 bytes of the ObjectId are timestamp which represent the ObjectId’s creation time.


In this example, the value of x would be: