MongoDB - ObjectId
MongoDB - Understanding ObjectId
Section titled “MongoDB - Understanding ObjectId”Every document in a MongoDB collection requires a unique _id field that acts as its primary key. If you don’t provide one, MongoDB automatically generates a unique ObjectId for the _id field when you insert the document.
An ObjectId is a 12-byte BSON type, meticulously crafted to ensure a high probability of uniqueness across different machines and at different times. It is composed of:
- A 4-byte timestamp value, representing the ObjectId’s creation, measured in seconds since the Unix epoch.
- A 5-byte random value (this has replaced the former machine + process ID for better distribution).
- A 3-byte incrementing counter, initialized to a random value.
This structure provides a default, sortable, and globally unique identifier for your documents.
Working with ObjectId
Section titled “Working with ObjectId”Generating a New ObjectId
Section titled “Generating a New ObjectId”You can generate a new ObjectId on demand in mongosh or your application driver.
// In mongosh> const newId = new ObjectId()> newIdObjectId("615cc1b3f72d5c4b1e9b1e2a")Extracting the Timestamp
Section titled “Extracting the Timestamp”Because the creation time is embedded within the ObjectId, you can extract it without needing a separate createdAt field (though explicit timestamps are often clearer). Use the getTimestamp() method:
> const myId = new ObjectId("615cc1b3f72d5c4b1e9b1e2a")> myId.getTimestamp()ISODate("2021-10-05T19:33:07.000Z")This feature makes ObjectIds naturally sortable by creation time.
Converting ObjectId to String
Section titled “Converting ObjectId to String”Often, you need to use the ObjectId’s value as a string, for example in a REST API URL, in a log file, or as a key in a JSON object being sent to a web client.
Modern Conversion Methods
Section titled “Modern Conversion Methods”Use the .toString() or .toHexString() methods to get the 24-character hexadecimal string representation. The legacy .str property is deprecated.
> const myId = new ObjectId()ObjectId("615cc204f72d5c4b1e9b1e2b")
> myId.toString()'615cc204f72d5c4b1e9b1e2b'
> myId.toHexString()'615cc204f72d5c4b1e9b1e2b'Practical Application and Best Practices
Section titled “Practical Application and Best Practices”- Immutability: The
_idfield is immutable. You cannot update the_idof a document after it has been inserted. If you need to change it, you must create a new document with the new_idand remove the old one. - Custom
_id: You can provide your own value for_id, as long as it’s unique within the collection. This is common when using a natural primary key, like a user’s email or a product SKU. However, these custom keys are not guaranteed to have the same useful sorting properties as an ObjectId. - Client-Side Generation: ObjectIds can be generated by the client-side driver before a document is even sent to the database. This allows you to know a document’s ID before inserting it, which can simplify application logic.