MongoDB ObjectId
In the previous chapters, we have already used MongoDB's ObjectId.
In this chapter, we will learn about 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 code
- The next 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.
Within a collection, each document has a unique "_id" value, which ensures that every document in the collection can be uniquely identified.
The main reason MongoDB uses ObjectId instead of other conventional practices (such as auto-incrementing primary keys) is because 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")
Timestamp of document creation
Since ObjectId stores a 4-byte timestamp, you don't need to save a timestamp field for your documents. You can use the getTimestamp function to obtain 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")
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:
5349b4ddd2781d08c09890f3Other Extensions