ObjectId in MongoDB

September 2022 · 2 minute read

You have seen the use of MongoDB ObjectId in previous chapters. In this chapter, we will understand the structure of ObjectId.

An ObjectId is a BSON type (12 bytes) with the following structure:

The first 4 bytes represent the number of seconds from UNIX Epoch.

The next 3 bytes is the machine id .

The next 2 bytes are the process id .

And the last 3 bytes are a random counting value .

MongoDB uses ObjectId as the default value of the _id field for each Document that is created while creating any Document. The complex combination of ObjectId makes all _id fields unique.

Create a new ObjectId in MongoDB

To create a new ObjectId, you use:

 > newObjectId = ObjectId () 

The above command returns the following unique created id:

 ObjectId ( "5349b4ddd2781d08c09890f3" ) 

In MongoDB, instead of creating ObjectId, you can also provide an ID of 12 bytes as follows:

 > myObjectId = ObjectId ( "5349b4ddd2781d08c09890f4" ) 

Get the Timestamp of a Document

By default, _id ObjectId stores a Timestamp of 4 bytes in length, so in most cases, you do not need to store the creation time of any Document. You can get the creation time of a Document using the getTimestamp method:

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

This command will return the creation time of this Document in ISO Date format:

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

Convert ObjectId into String in MongoDB

In some cases, you may need the value of ObjectId in string format. To convert ObjectId into a string, you use:

 > newObjectId . str 

The above code will return Guid's string format:

 5349b4ddd2781d08c09890f3 

According to Tutorialspoint

Previous article: Limitations of index in MongoDB

Next post: Map Reduce in MongoDB

ncG1vNJzZmismaXArq3KnmWcp51kvKO2xJyropxdnrtuuc6nnqickg%3D%3D