Skip to content
Related Articles
Get the best out of our app
Open App

Related Articles

What is ObjectId in MongoDB

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

Every document in the collection has an “_id” field that is used to uniquely identify the document in a particular collection it acts as the primary key for the documents in the collection. “_id” field can be used in any format and the default format is ObjectId of the document.

An ObjectID is a 12-byte Field Of BSON type

  • The first 4 bytes representing the Unix Timestamp of the document
  • The next 3 bytes are the machine Id on which the MongoDB server is running.
  • The next 2 bytes are of process id
  • The last Field is 3 bytes used for increment the objectid.

Format of ObjectId:


ObjectId accepts one parameter which is optional Hexadecimal ObjectId in String.

We can give our own ObjectId to the document but it must be unique.



Database : gfg

Collection: student_gfg

Methods of ObjectId:

  1. str: Returns the hexadecimal string format of the ObjectId
  2. ObjectId.getTimestamp() : It returns the timestamp portion of the object as a Date.
  3. ObjectId.valueOf(): It return the hexadecimal format of a given String Literal.
  4. ObjectId.toString(): This method returns ObjectId in String format in javascript representation.

1.Creating ObjectId: To generate new ObjectId of particular document.

newObjectId = ObjectId()



2.Timestamp of the ObjectID: It returns the timestamp information of the object as a Date in ISO format.

var id =new ObjectId();    




3.Converting ObjectId to string: ObjectId can be converted into string format.

 new ObjectId().str



My Personal Notes arrow_drop_up
Last Updated : 01 Nov, 2020
Like Article
Save Article
Similar Reads