Web Programming TutorialsLearn About the Structure of ObjectId in MongoDB

Learn About the Structure of ObjectId in MongoDB

Structure
In this article, we are going to learn about the structure of the MongoDB ObjectId. Before, we get into the details on how and why the ObjectId is created in the MongoDB, let us first understand the structure of the ObjectId.

Structure of ObjectId in MongoDB

An ObjectId in MongoDB is a 12-byte BSON type.
In the 12-byte structure, the first 4 bytes of the ObjectId represent the time in seconds since the UNIX epoch.
The next 3 bytes of the ObjectId represent the machine identifier.
The next 2 bytes of the ObjectId represent the process ID.
And the last 3 bytes of the ObjectId represent a random counter value.

These 12 bytes altogether uniquely identifies a document within the MongoDB collection and serves as a primary key for that document. ObjectId is the default value of _id field of each document and its complexity helps to fetch a unique _id field for a particular document in the MongoDB.

How to generate the ObjectId for a document in the MongoDB?
The answer is very simple, these ObjectIds associated with the documents could be generated in the MongoDB when we insert a document in the MongoDB Collection. The following are the syntaxes through which we can insert data into the MongoDB collection by using either MongoDB’s ‘insert ()’ or ‘save ()’ method.

Syntax
The following is the basic syntax for insert () command in MongoDB.

> db.COLLECTION_NAME.insert(document)

Example
The following is an example on using the insert () statement.

> db.test.insert ( { title: 'Insert Statement',description: 'MongoDB Tutorial', company: 'Eduonix Learning Inc.'})
WriteResult({ "nInserted" : 1 })
> db.test.find()
{ "_id" : ObjectId("5813eed6e6893b80c9ae5bba"), "abc" : 100 }
{ "_id" : ObjectId("5814c9b689c20c164089fbe7"), "title" : "Insert Statement", "description" : "MongoDB Tutorial", "company" : "Eduonix Learning Inc." }
>

Img1
Explanation of the code

Here, we are using default ‘test’ collection name of MongoDB.
We are issuing an insert command without specifying the _id parameter. In such a case MongoDB will generate a unique ObjectId for this document with three fields i.e. title, description and company.
_id parameter is a 12 bytes hexadecimal number unique assigned to every document in a MongoDB collection. This is how these 12 bytes are divided as follows:

_id: ObjectId(4 bytes are timestamp, 3 bytes are machine id, 2 bytes are process id, and 3 bytes are incrementer)

Note: – We can insert multiple documents in a single query by using an array of documents inside an ‘insert ()’ command.

> db.test.save ( [ { title: 'Array1', description: 'Mongo1', company: 'Eduonix', tags: ['abc', 'def', 'ijk'] }, {title: 'Array2', description: 'Mongo2', company: 'Eduonix', tags: ['123', '456', '789'] } ] )
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
>

Img2
Syntax
The following is the basic syntax for save () command in MongoDB.

> db.COLLECTION_NAME.save(document)

Example
The following is an example on using the save () statement.

> db.test.save ( { title: 'save Statement',description: 'MongoDB Tutorial2', company: 'Eduonix Learning Inc.'})
WriteResult({ "nInserted" : 1 })
> db.test.save ( {"_id" : ObjectId("5813eed6e6893b80c9ae5bba"), title: 'save Statement with id', description: 'MongoDB Tutorial save with object id', company: 'Eduonix Learning Inc.'})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.test.find()
{ "_id" : ObjectId("5813eed6e6893b80c9ae5bba"), "title" : "save Statement with id", "description" : "MongoDB Tutorial save with object id", "company" : "Eduonix Learning Inc." }
{ "_id" : ObjectId("5814c9b689c20c164089fbe7"), "title" : "Insert Statement", "description" : "MongoDB Tutorial", "company" : "Eduonix Learning Inc." }
{ "_id" : ObjectId("5814cbb389c20c164089fbe8"), "title" : "save Statement", "description" : "MongoDB Tutorial2", "company" : "Eduonix Learning Inc." }
>

Note: – The ‘save ()’ method works in a similar way as that of an ‘insert ()’ method when do not specify _id in the document. If we specify an id then the ‘save ()’ method will replace the whole data of the document containing _id (i.e. modifying the existing record) as given in ‘save ()’ method.

Alternative ways to create a new ObjectId
We can create an ObjectId by calling an in-built function ObjectId () which is present in the MongoDB. The following is the syntax.

Microsoft Windows [Version 10.0.14393]
(c) 2016 Microsoft Corporation. All rights reserved.

C:\Users\Aparajita>mongo.exe
'mongo.exe' is not recognized as an internal or external command,
operable program or batch file.

C:\Users\Aparajita>cd C:\Program Files\MongoDB\Server\3.2\bin

C:\Program Files\MongoDB\Server\3.2\bin>mongo
MongoDB shell version: 3.2.10
connecting to: test
> getNewObjectId = ObjectId()
ObjectId("58ce9d76c65f10f0e30f5510")
>

Output
When we will execute the ObjectId () method of the MongoDB, it will automatically return a 12-byte unique ObjectId (here 58ce9d76c65f10f0e30f5510). Not only this, we can also suggest our 12-byte ObjectId to the MongoDB with the help of the following syntax.

> myNewObjectIdGen = ObjectId("5813eed6e6893b80c9ae5bba")
ObjectId("5813eed6e6893b80c9ae5bba")
>

Generating Timestamp of a Document in the MongoDB
As mentioned before in this article that the first 4 bytes of the 12-byte BSON type ObjectId represent the time in seconds since the UNIX epoch. Therefore, we can use this 4-byte timestamp to generate or fetch the timestamp with the help of the following syntax.

> ObjectId("58ce9d76c65f10f0e30f5510").getTimestamp()
ISODate("2017-03-19T15:02:14Z")
>

Output
When we will execute the above syntax in the MongoDB, then we can observe the returned created date and time of that document in the ISO date format.

Conversion of ObjectId into String
There may be the situations, when you are developing your application in the MongoDB and you may want to access the value of the ObjectId as a String in the string format. The MongoDB has provided the provision for that to procure the string out of the ObjectId with the help of the following syntax.

> getNewObjectId.str
58ce9d76c65f10f0e30f5510

Output
When we will execute the above syntax in the MongoDB, then we can observe the returned string as 58ce9d76c65f10f0e30f5510 in the string format.

Conclusion
In this article, we discussed the structure of the 12-byte ObjectId in the MongoDB, which serves as the primary key to uniquely identify a document in the MongoDB. Further, we discussed the number of ways through which we can generate the ObjectId in the MongoDB and fetch the timestamp and the string format from this ObjectId in the MongoDB.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -