The MongoDB Data Model
BSON types, ObjectIds, and document structure
Skills taught: mongodb.data-model
BSON: Binary JSON
MongoDB stores documents as BSON (Binary JSON), an extension of JSON that adds type information and binary encoding. BSON supports all JSON types plus several additional ones that are essential for a database: Date, ObjectId, Binary, Decimal128, and more.
You write documents in regular JSON (or JavaScript objects), and the MongoDB driver automatically converts them to BSON before sending to the server. When reading, BSON is decoded back to native types in your language.
BSON Type Reference
// BSON types used in a real document
const user = {
_id: new ObjectId(), // ObjectId — 12-byte unique ID
name: "Alice Sharma", // String
age: 30, // Int32 (or Double in some drivers)
score: 95.7, // Double (64-bit float)
balance: Decimal128("1234.56"), // Decimal128 — precise money values
active: true, // Boolean
tags: ["admin", "editor"], // Array
address: { // Embedded document (nested object)
city: "Delhi",
zip: "110001"
},
createdAt: new Date(), // Date (stored as 64-bit UTC ms since epoch)
updatedAt: null, // Null
avatar: Binary(Buffer.alloc(10)), // Binary — for files, images
pattern: /^[a-z]+$/i, // Regular expression
};
// Check the BSON type of a value
console.log(user._id instanceof ObjectId); // true
console.log(user._id.toString()); // "507f1f77bcf86cd799439011"
- ObjectId
- A 12-byte unique identifier automatically generated for the _id field of each document. Contains a 4-byte timestamp, 5-byte random value, and 3-byte counter. Because of the timestamp component, ObjectIds are roughly sortable by creation time.
The _id Field
Every MongoDB document must have a unique _id field. If you don't provide one, MongoDB automatically generates an ObjectId. The _id field is always indexed — queries by _id are instantaneous.
// Auto-generated ObjectId
const id = new ObjectId();
console.log(id.toString()); // "6752ab3f1234567890abcdef"
console.log(id.getTimestamp()); // Date object — when it was created
// Extract creation timestamp from any ObjectId
const doc = await users.findOne({ name: 'Alice' });
console.log(doc._id.getTimestamp()); // When Alice's document was created
// Custom _id (e.g., use email as ID)
await users.insertOne({
_id: 'alice@example.com', // custom string _id
name: 'Alice'
});
// Now you can find Alice without knowing her ObjectId:
await users.findOne({ _id: 'alice@example.com' });
Tip: Always let MongoDB generate _id using ObjectId unless you have a natural unique key (like email or username). ObjectIds are globally unique across machines and contain a creation timestamp for free.
Using Dates Correctly
One of the most common mistakes in MongoDB is storing dates as strings instead of BSON Date objects. Always use new Date() so you can sort, compare, and query date ranges correctly.
// BAD: dates as strings — cannot sort, range query, or extract month
await events.insertOne({
name: 'Conference',
date: '2026-06-15' // string — will sort lexicographically, not chronologically
});
// GOOD: use BSON Date
await events.insertOne({
name: 'Conference',
date: new Date('2026-06-15') // ISODate — sortable, comparable, math-friendly
});
// Now you can query date ranges correctly:
const upcoming = await events.find({
date: { $gte: new Date() } // all events from now onwards
}).sort({ date: 1 }).toArray();
// Extract year from date in aggregation:
db.events.aggregate([
{ $project: { year: { $year: '$date' }, name: 1 } }
]);
Warning: Never store dates as strings like '2026-06-15'. Date comparison and range queries won't work correctly. Use new Date() or ISODate() in mongosh to store proper BSON Date values.
Frequently Asked Questions
Can I use a custom _id?
Yes. Set _id to any unique value: a string email, an integer, or any value you choose. Just ensure uniqueness — MongoDB will reject duplicate _id inserts with an E11000 duplicate key error.
What is the difference between Double and Decimal128?
Double is a 64-bit IEEE 754 floating-point, which is fast but can have rounding errors (0.1 + 0.2 = 0.30000000000000004). Decimal128 is an arbitrary-precision decimal type that is accurate to 34 significant digits — use it for monetary values to avoid rounding bugs.
What is BSON and why doesn't MongoDB just use JSON?
JSON is text-based and typeless — it cannot distinguish a date from a string, or store binary data. BSON is a binary format that adds explicit type tags and length prefixes to each field, making it faster to parse and encode, and supporting types that JSON doesn't have.