0
0
MongodbHow-ToBeginner · 3 min read

How ObjectId is Generated in MongoDB: Explained Simply

In MongoDB, an ObjectId is generated as a 12-byte unique identifier composed of a 4-byte timestamp, a 5-byte random value, and a 3-byte incrementing counter. This structure ensures each ObjectId is unique and sortable by creation time.
📐

Syntax

The ObjectId is a 12-byte BSON type used as a unique identifier for documents in MongoDB collections. It is usually generated automatically when a document is inserted without an explicit _id field.

The 12 bytes are divided as follows:

  • 4 bytes: Timestamp in seconds since Unix epoch
  • 5 bytes: Random value unique to the machine and process
  • 3 bytes: Incrementing counter, starting from a random value
mongodb
ObjectId: 12 bytes total
| 4 bytes timestamp | 5 bytes random value | 3 bytes counter |
💻

Example

This example shows how to generate an ObjectId in MongoDB using the Node.js driver and how to extract its timestamp.

javascript
const { ObjectId } = require('mongodb');

// Generate a new ObjectId
const id = new ObjectId();

// Print the ObjectId string
console.log('Generated ObjectId:', id.toHexString());

// Extract and print the timestamp from ObjectId
console.log('Timestamp:', id.getTimestamp());
Output
Generated ObjectId: 64b7f2e4a1b2c3d4e5f67890 Timestamp: 2023-07-19T12:34:12.000Z
⚠️

Common Pitfalls

Some common mistakes when working with ObjectId include:

  • Assuming ObjectId is a simple random string; it encodes creation time and uniqueness.
  • Manually creating ObjectId strings without proper format leads to errors.
  • Using ObjectId as a timestamp substitute without converting it properly.

Always use MongoDB drivers' built-in methods to generate and parse ObjectId.

javascript
const { ObjectId } = require('mongodb');

// Wrong: creating ObjectId from invalid string
try {
  const badId = new ObjectId('12345'); // Too short
} catch (e) {
  console.error('Error:', e.message);
}

// Right: create new ObjectId properly
const goodId = new ObjectId();
console.log('Valid ObjectId:', goodId.toHexString());
Output
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters Valid ObjectId: 64b7f2e4a1b2c3d4e5f67890
📊

Quick Reference

ComponentSize (bytes)Description
Timestamp4Seconds since Unix epoch, ensures sorting by creation time
Random Value5Unique machine and process identifier
Counter3Incrementing counter to avoid collisions

Key Takeaways

MongoDB's ObjectId is a 12-byte unique identifier combining timestamp, random value, and counter.
The first 4 bytes encode the creation time, making ObjectIds sortable by insertion order.
Always use MongoDB drivers to generate and parse ObjectIds to avoid format errors.
ObjectId is not just a random string; it contains meaningful data for uniqueness and ordering.