May 17, 2021 MongoDB
We've already used MongoDB's Object ID in the previous chapters.
In this section, we'll look at the structure of ObjectId.
ObjectId is a 12-byte BSON type data in the following format:
Documents stored in MongoDB must have a "_id" key. The value of this key can be of any type and is an ObjectId object by default.
Within a collection, each collection has a unique "_id" value to ensure that each document in the collection is uniquely identified.
MongoDB uses ObjectId instead of other more conventional practices, such as automatically increasing the primary key, because synchronization on multiple servers automatically increases the primary key value is labor-stressing and time-saving.
Use the following code to generate a new ObjectId:
>newObjectId = ObjectId()
The statement above returns the following unique generated id:
ObjectId("5349b4ddd2781d08c09890f3")
You can also use the generated id instead of the MongoDB auto-generated ObjectId:
>myObjectId = ObjectId("5349b4ddd2781d08c09890f4")
Because 4 bytes of timestamps are stored in ObjectId, you don't need to save timestamp fields for your document, and you can get 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")
In some cases, you may need to convert ObjectId to string format. Y ou can use the following code:
>new ObjectId.str
The above code returns a string in Guide format:
5349b4ddd2781d08c09890f3