Understand _id and ObjectId in MongoDB.

by Virender
May 27, 2015
MongoDB use _id for uniquely identity column in document its behave as a Primary Key.  MongoDB use Objectid as the default value for _id. BSON ObjectId is generated by MongoDB drivers . In static increment nature. If MongoDB Client not add _id field then MongoDB automatically create _id field for document to uniquely identify column.

Its very complex combination of Objectids makes all the _id fields unique. We have option to into own value into _id field.

Object ID= [4 bytes seconds since epoch, 3 bytes machine hash, 2 bytes process ID, 3 bytes counter]

An ObjectId is a 12-byte BSON type having the following structure:

•    The first 4 bytes representing the seconds since the unix epoch
•    The next 3 bytes are the machine identifier
•    The next 2 bytes consists of process id
•    The last 3 bytes are a random counter value

Benefit of ObjectIDs

  • ObjectId make document unique
  • ObjectID store timestamp .we Can easily get creation time of ObjectIds by using getTimeStamp() function. So, no more need to column like createDate or insertedDate
  • Index automatically created into _id field for improve index. It’s helpful in sorting.

How Objectids generate in static increment nature.

In image see last four digit its generating in series like “bca’,”bcb’,”bcc”,”bcd”……

Creating New ObjectId

To generate a new ObjectId use the following code:

Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id:

Insert own unique key

We can insert own unique value for _id.

db.foo.insert({_id: ‘abc’})

Creation Timestamp of a Document

Objectid store 4 byte tmestamp. You can fetch the creation time of a document using getTimeStamp function :

 when you will run command on console. This will return the creation time of this document in ISO Date format:


Convert ObjectId to String

In some cases you may need the value of ObjectId in string format. To convert the ObjectId in string use the following code:

x.str (x is object here)Or

this command will return the string format of object like this




Notify of
Inline Feedbacks
View all comments

Related posts