We have used MongoDB’s object Id (ObjectId) in the previous chapters.
In this chapter, we will learn about the structure of ObjectId.
ObjectId is a 12-byte BSON type data in the following format:
The first four bytes represent a timestamp
The next three bytes are machine identification codes.
The next two bytes are made up of process id (PID)
The last three bytes are random numbers.
Documents stored in MongoDB must have a “_ id” key. The value of this key can be of any type, and the default is an ObjectId object.
在一个集合里面,每个文档都有唯一的”_id”值,来确保集合里面每个文档都能被唯一标识。
MongoDB uses ObjectId rather than the main reason for other more conventional practices, such as auto-incrementing primary keys, because it is laborious and time-consuming to increase primary key values synchronously on multiple servers. Generate a new ObjectId using the following code: The above statement returns the following unique generated id: You can also use the generated id instead of the ObjectId automatically generated by MongoDB: Because the 4-byte timestamp is stored in ObjectId, you don’t need to save the timestamp field for your document, you can use the getTimestamp function to get the creation time of the document: The above code returns the creation time of the document in ISO format: In some cases, you may need to convert ObjectId to string format. You can use the following code: The above code returns a string in Guid format: 3.38.1. Create a new ObjectId ¶
>newObjectId = ObjectId()
ObjectId("5349b4ddd2781d08c09890f3")
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
3.38.2. Timestamp when the document was created ¶
>ObjectId("5349b4ddd2781d08c09890f4").getTimestamp()
ISODate("2014-04-12T21:49:17Z")
3.38.3. Convert ObjectId to string ¶
>new ObjectId().str
5349b4ddd2781d08c09890f3