Mongodb Objectid
# MongoDB ObjectId
* * *
In the previous few chapters, we have already used MongoDB's ObjectId.
In this chapter, we will understand the structure of ObjectId.
ObjectId is a 12-byte BSON type data, with the following format:
* The first 4 bytes represent a timestamp
* The next 3 bytes are the machine identifier code
* The following two bytes consist of the process ID (PID)
* The last three bytes are a random value.
Documents stored in MongoDB must have an "_id" key. The value of this key can be of any type, and by default, it is an ObjectId object.
In a collection, each document has a unique "_id" value to ensure that every document in the collection can be uniquely identified.
The main reason MongoDB uses ObjectId instead of other more conventional methods (such as auto-incrementing primary keys) is that synchronizing auto-incrementing primary key values across multiple servers is both effortful and time-consuming.
* * *
## Creating a New ObjectId
Use the following code to generate a new ObjectId:
>newObjectId = ObjectId()
The above statement returns the following uniquely generated id:
ObjectId("5349b4ddd2781d08c09890f3")
You can also use the generated id to replace MongoDB's automatically generated ObjectId:
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
* * *
## Creating a Timestamp for a Document
Since ObjectId stores a 4-byte timestamp, you do not need to save a timestamp field for your document. You can use the getTimestamp function to get the creation time of the document:
>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
The above code will return the document creation time in ISO format:
ISODate("2014-04-12T21:49:17Z")
* * *
## Converting ObjectId to String
In some cases, you may need to convert an ObjectId to a string format. You can use the following code:
>new ObjectId().str
The above code will return a string in GUID format:
5349b4ddd2781d08c09890f3
YouTip