MongoDB ObjectId
In the previous chapters we have used MongoDB's object Id (ObjectId).
In this chapter, we will learn about the structure of ObjectId.
ObjectId is a 12-byte BSON type of data with the following format:
- The first 4 bytes represent the timestamp
- The next 3 bytes are the machine identification code
- The following two bytes consist of the process id (PID)
- The last three bytes are a random number.
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 approaches (such as auto-incrementing primary keys) is that synchronizing auto-incrementing primary key values across multiple servers is both 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 uniquely generated id:
ObjectId("5349b4ddd2781d08c09890f3")
You can also use the generated id to replace the ObjectId automatically generated by MongoDB:
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
The timestamp of document creation
Since ObjectId stores a 4-byte timestamp, you do not need to save a timestamp field for your document; you can obtain the document's creation time through the getTimestamp function:
>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
The above code returns the document creation time in ISO format:
ISODate("2014-04-12T21:49:17Z")
Convert ObjectId to a string
In some cases, you may need to convert an ObjectId to string format. You can use the following code:
>new ObjectId().str
The above code returns a string in Guid format::
5349b4ddd2781d08c09890f3