MongoDB ObjectId
In the previous chapters we have used MongoDB’s object Id (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 identification code
The next two bytes consist of the process id (PID)
The last three bytes are random numbers.
Documents stored in MongoDB must have an "_id" key. The value of this key can be of any type, and the default is an ObjectId object.
In a collection, each document has a unique "_id" value to ensure that each document in the collection can be uniquely identified.
The main reason why MongoDB uses ObjectId instead of other more conventional methods (such as automatically increased primary keys) is because in multiple Synchronizing and automatically increasing the primary key value on the server is laborious and time-consuming.
Create a new ObjectId
Use the following code to generate a new ObjectId:
>newObjectId = ObjectId()
The above statement returns the following unique generated id:
ObjectId("5349b4ddd2781d08c09890f3")
You can also use the generated id to replace the ObjectId automatically generated by MongoDB:
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
Time stamp of creating the document
Since the ObjectId stores a 4-byte timestamp, So you don’t need to save the timestamp field for your document. You can get the creation time of the document through the getTimestamp function:
>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
The above code will return the document creation time in ISO format:
ISODate("2014-04-12T21:49:17Z")
Convert ObjectId to String
In some cases, you may need to convert ObjectId to string format. You can use the following code:
>new ObjectId().str
The above code will return a string in Guid format: :
5349b4ddd2781d08c09890f3