Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

MongoDB ObjectId


May 17, 2021 MongoDB


Table of contents


MongoDB ObjectId


We've already used MongoDB's Object ID in the previous chapters.

In this section, we'll look at the structure of ObjectId.

ObjectId is a 12-byte BSON type data in the following format:

  • The first four bytes represent timestamps
  • The next three bytes are the machine identification code
  • The two bytes immediately followed are made up of process id (PID)
  • The last three bytes are random numbers.

Documents stored in MongoDB must have a "_id" key. The value of this key can be of any type and is an ObjectId object by default.

Within a collection, each collection has a unique "_id" value to ensure that each document in the collection is uniquely identified.

MongoDB uses ObjectId instead of other more conventional practices, such as automatically increasing the primary key, because synchronization on multiple servers automatically increases the primary key value is labor-stressing and time-saving.


Create a new ObjectId

Use the following code to generate a new ObjectId:

>newObjectId = ObjectId()

The statement above returns the following unique generated id:

ObjectId("5349b4ddd2781d08c09890f3")

You can also use the generated id instead of the MongoDB auto-generated ObjectId:

>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")

Create a timestamp for the document

Because 4 bytes of timestamps are stored in ObjectId, you don't need to save timestamp fields for your document, and you can get the document's creation time through the getTimestamp function:

>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()

The above code returns the document creation time in ISO format:

ISODate("2014-04-12T21:49:17Z")

ObjectId is converted to a string

In some cases, you may need to convert ObjectId to string format. Y ou can use the following code:

>new ObjectId.str

The above code returns a string in Guide format:

5349b4ddd2781d08c09890f3