QA
Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?

❓ Interview Prompt: Explain 12-byte BSON ObjectId structure (4-byte timestamp, 5-byte random value, 3-byte counter), extraction, and uniqueness.

A MongoDB ObjectId is a 12-byte binary BSON value that guarantees global uniqueness across distributed nodes without central locking:

12-Byte Breakdown:

•
Bytes 0-3 (4 bytes): Unix epoch timestamp (in seconds).
•
Bytes 4-8 (5 bytes): Random value unique to the machine and process.
•
Bytes 9-11 (3 bytes): Incrementing counter initialized to a random value.

Code Implementation Example

typescript
import { Types } from 'mongoose';

const id = new Types.ObjectId();

// Extract creation timestamp embedded inside ObjectId!
const creationDate = id.getTimestamp();
console.log('ObjectId: ${id.toHexString()}, Created At: ${creationDate.toISOString()}');
💡Extracting creation timestamp directly from a 12-byte MongoDB ObjectId.
🎯 Interview Key Takeaway

MongoDB ObjectIds contain an embedded 4-byte Unix creation timestamp, allowing sorting by creation time without a separate createdAt field.

#ObjectId#BSON#MongoDB#Beginner
Back to all MongoDB & Mongoose Questions→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

How do basic CRUD operations work in MongoDB (find, insertOne, updateOne, deleteOne)?