Hiprup

What is the _id field and ObjectId in MongoDB?

Every MongoDB document has a unique _id field that serves as its primary key. If you don't provide one, MongoDB generates an ObjectId automatically.

  • ObjectId — 12-byte value: 4-byte timestamp + 5-byte random + 3-byte counter. Roughly sortable by creation time.

  • Indexed automatically — unique index on _id exists from the start; cannot be dropped.

  • Custom values allowed — supply any unique value (string, integer, UUID) instead of ObjectId.

  • Embeds the timestampObjectId.getTimestamp() returns the creation moment without a separate column.

  • Immutable — once set, can't be updated.

// Auto-generated ObjectId
db.users.insertOne({ name: 'John' });
// { _id: ObjectId('507f1f77bcf86cd799439011'), name: 'John' }

// Extract creation time from ObjectId
const id = ObjectId('507f1f77bcf86cd799439011');
console.log(id.getTimestamp()); // 2012-10-17T20:46:31.000Z

// Custom _id
db.products.insertOne({ _id: 'SKU-001', name: 'Widget', price: 9.99 });

// _id is automatically indexed and unique
db.users.insertOne({ _id: 1, name: 'Alice' });
db.users.insertOne({ _id: 1, name: 'Bob' }); // Error: duplicate key

ObjectId is auto-generated with timestamp + random + counter. getTimestamp() extracts the creation time (no need for a separate createdAt field). Custom _id can be any type (string 'SKU-001' here).

Duplicate _id throws an error (unique index).

Know the ObjectId structure: 4-byte timestamp + 5-byte random + 3-byte counter = 12 bytes. getTimestamp() extracts creation time. _id can be any type (not just ObjectId). _id is automatically indexed and unique. No need for auto-increment — ObjectId handles uniqueness globally.

What is the _id field and ObjectId in MongoDB? | Hiprup