Open In App

What is ObjectId in MongoDB

Improve
Improve
Like Article
Like
Save
Share
Report

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(<hexadecimal>)

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.

*db.<collectionname>.insertOne({"_id":"231231"})

Example:

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()

Output:

ObjectId(“5f92cbf10cf217478ba93561”)

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

var id =new ObjectId();    

 id.getTimestamp()

Output:

ISODate(“2020-10-23T12:32:42Z”)

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

 new ObjectId().str

Output:

5f92cdce0cf217478ba93563


Last Updated : 01 Nov, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads