
ObjectId-MongoDB
We have been using MongoDB Object Id in all the previous chapters. In this chapter, we will understand the structure of ObjectId.
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
MongoDB uses ObjectIds as the default value of _id field of each document, which is generated while the creation of any document. The complex combination of ObjectId makes all the _id fields unique.
Creating New ObjectId
To generate a new ObjectId use the following code −
>newObjectId = ObjectId()
The above statement returned the following uniquely generated id −
ObjectId("5349b4ddd2781d08c09890f3")
Instead of MongoDB generating the ObjectId, you can also provide a 12-byte id −
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")

Creating Timestamp of a Document
Since the _id ObjectId by default stores the 4-byte timestamp, in most cases you do not need to store the creation time of any document. You can fetch the creation time of a document using getTimestamp method −
>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
This will return the creation time of this document in ISO date format −
ISODate("2014-04-12T21:49:17Z")
Converting ObjectId to String
In some cases, you may need the value of ObjectId in a string format. To convert the ObjectId in string, use the following code −
>newObjectId.str
The above code will return the string format of the Guid −
5349b4ddd2781d08c09890f3
MongoDB stores data in flexible, JSON-like documents, meaning fields can vary from document to document and data structure can be changed over time
The document model maps to the objects in your application code, making data easy to work with
Ad hoc queries, indexing, and real time aggregation provide powerful ways to access and analyze your data
MongoDB is a distributed database at its core, so high availability, horizontal scaling, and geographic distribution are built in and easy to use
MongoDB is free to use. Versions released prior to October 16, 2018 are published under the AGPL. All versions released after October 16, 2018, including patch fixes for prior versions, are published under the Server Side Public License (SSPL) v1.
MongoDB is designed to meet the demands of modern apps with a technology foundation that enables you through:
The document data model – presenting you the best way to work with data.
A distributed systems design – allowing you to intelligently put data where you want it.
A unified experience that gives you the freedom to run anywhere – allowing you to future-proof your work and eliminate vendor lock-in.
With these capabilities, you can build an Intelligent Operational Data Platform, underpinned by MongoDB. Download the Architecture Guide where we dive deeper into the technology foundations of MongoDB.