MongoDB ObjectId - MongoDB

What is the use of ObjectId in MongoDB?

Since we have used MongoDB Object Id in all the previous chapters, in this chapter, we will explain the structure of ObjectId.

An ObjectId is a 12-byte BSON type having below structure

  • First 4 bytes representing the seconds since the unix epoch
  • Next 3 bytes are the machine identifier
  • Next 2 bytes consists of process id
  • Last 3 bytes are random counter values

MongoDB uses ObjectIds as default value of _id field of each document, which is generated while creating any document. Complex combination of ObjectId makes all the _id fields unique.

Creating New ObjectId

For generating a new ObjectId use below code

Above statement returns below shown uniquely generated id

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

Creating Timestamp of a Document

As the _id ObjectId by default stores 4-byte timestamp, in most cases you don’t have to store the creation time of any document. Creation time of a document can be fetched using getTimestamp method

This returns the creation time of this document in ISO date format

Converting ObjectId to String

In some cases, value of ObjectId is needed in a string format. To convert the ObjectId in string, use below code

Above code returns the string format of the Guid

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

MongoDB Topics