MongoDB ObjectId
In the previous 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 the timestamp
- The next 3 bytes are the machine identifier
- The following 2 bytes consist of the process id (PID)
- The last 3 bytes are a random number.
Every document stored in MongoDB must have an "_id" key. The value of this key can be of any type, with ObjectId being the default.
Within a collection, each document has a unique "_id" value to ensure that each document in the collection can be uniquely identified.
The main reason MongoDB uses ObjectId instead of other conventional methods (like auto-incremented primary keys) is that synchronizing auto-incremented primary key values across multiple servers is both laborious 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 a generated id to replace the ObjectId automatically generated by MongoDB:
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
Timestamp of Document Creation
Since the ObjectId stores a 4-byte timestamp, you do not need to save a timestamp field for your document. You can obtain the creation time of the document using the getTimestamp function:
>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
The above code will return the creation time of the document in ISO format:
ISODate("2014-04-12T21:49:17Z")
Converting ObjectId to String
In some cases, you may need to convert the ObjectId to a string format. You can use the following code:
>new ObjectId().str
The above code will return the string in GUID format:
5349b4ddd2781d08c09890f3