134: MongoDB Fundamentals — Documents, BSON, Atlas, Data Types, and When to Use MongoDB
Learning objectives
You will learn to:
- explain what MongoDB is;
- distinguish document databases from relational databases;
- understand database, collection, document, field, and
_id; - understand BSON versus JSON;
- use common BSON data types correctly;
- understand
ObjectId; - install/connect to MongoDB locally or through Atlas;
- use
mongosh; - create collections and inspect documents;
- understand flexible schema versus schema-less misconception;
- decide when MongoDB is a good or poor fit;
- understand MongoDB 8.3 as the current stable release line in 2026.
Baseline
As of August 2026, MongoDB 8.3 is the current stable release line.
Production deployments should run supported, patched versions and follow MongoDB's versioning/upgrade guidance.
Check:
db.version()
in mongosh.
What MongoDB is
MongoDB is a document-oriented database.
Instead of relational rows:
users table orders table order_items table
MongoDB stores BSON documents in collections.
Example:
{
_id: ObjectId("..."),
customerId: ObjectId("..."),
status: "pending",
items: [
{
productId: ObjectId("..."),
name: "Notebook",
quantity: 2,
pricePaise: 12000
}
],
totals: {
subtotalPaise: 24000,
taxPaise: 4320,
totalPaise: 28320
},
createdAt: ISODate("2026-08-27T10:00:00Z")
}
Related data can be embedded directly inside one document.
This is powerful when the application usually reads/writes the data together.
Core terminology
server / deployment database collection document field index query cursor aggregation pipeline replica set sharded cluster
Example:
database: commerce collection: orders document: one order field: status
BSON versus JSON
JSON supports a small type set:
string number boolean null array object
BSON is a binary serialization format used by MongoDB and supports more data types.
Important BSON types include:
String Double Int32 Int64/Long Decimal128 Boolean Date ObjectId Array Embedded Document Binary Regular Expression Timestamp Null MinKey MaxKey
Some historical/deprecated BSON types may still appear in old data/docs; do not choose obsolete types for new schemas.
Why BSON types matter
This:
{ amount: 100 }
and:
{ amount: "100" }
are different types.
A query:
db.orders.find({
amount: 100
})
does not mean “coerce every string 100.”
Type consistency affects:
- queries;
- sorting;
- indexes;
- aggregation;
- validation.
Flexible schema does not mean type discipline is irrelevant.
_id
Every document has a unique _id field.
If omitted, drivers commonly generate an ObjectId.
Example:
{
_id: ObjectId("66d0...")
}
You can use another unique type/value for _id, but choose deliberately.
Do not change _id after insertion.
ObjectId
ObjectId is a 12-byte BSON identifier type.
It is:
- compact;
- generated client-side by drivers;
- roughly time-sortable due to timestamp component;
- not a secret;
- not authorization.
Never assume:
unpredictable ObjectId = secure access control
A user who learns another tenant's ID still must be blocked by server authorization/query scoping.
ObjectId conversion
In shell:
ObjectId("66d0...")
In Node driver:
import { ObjectId } from 'mongodb';
const id = new ObjectId(rawId);
Validate string format before using.
Do not query:
{ _id: req.params.id }
when _id is ObjectId; type mismatch returns nothing.
Dates
Store actual BSON Date:
{
createdAt: new Date()
}
not formatted strings:
{
createdAt: "27/08/2026"
}
Date type supports comparison/indexing.
Application can format for locale at presentation.
Money
Do not casually use floating-point Double for exact financial arithmetic.
Options include:
Integer minor units
{
amountPaise: NumberLong("12500")
}
or safe integer within JS/driver limitations.
Decimal128
{
amount: Decimal128("125.00")
}
Use a consistent domain strategy.
Understand driver conversion; JavaScript Number cannot exactly represent every Int64/decimal value.
Integers
BSON distinguishes Int32, Int64, Double.
JavaScript's ordinary number is IEEE-754 double.
MongoDB Node driver has BSON helper types for exact 64-bit/decimal values.
Do not silently convert huge Int64 to JS number if it exceeds safe integer range.
Number.isSafeInteger(...)
matters.
Binary
Useful for:
- hashes;
- UUID encodings;
- encrypted values;
- small binary metadata.
For large files, MongoDB GridFS is a specialized mechanism, but object storage is often a better architecture for application files.
Advanced lesson covers GridFS.
Arrays
{
tags: ["node", "mongodb"],
items: [
{ sku: "A", quantity: 2 },
{ sku: "B", quantity: 1 }
]
}
MongoDB can query/index array fields.
Arrays can grow a document dramatically; unbounded arrays are a common modeling mistake.
Embedded documents
{
shippingAddress: {
line1: "...",
city: "...",
postalCode: "..."
}
}
Embedding is a core MongoDB modeling tool.
But “embed everything” is not the rule.
Access patterns and document growth decide.
Lesson 135 covers modeling deeply.
MongoDB document limits
MongoDB documents have a maximum BSON document size.
Do not design:
one user document → array of every event forever
Unbounded growth will eventually fail or become inefficient.
Know platform limits from current docs.
Flexible schema
MongoDB permits documents in one collection to have different shapes.
Example:
{ type: "email", email: "a@example.com" }
{ type: "phone", phone: "+..." }
This is useful for polymorphic data.
But production collections still need intentional contracts.
MongoDB supports collection schema validation.
Applications can also validate using driver/ODM/schema libraries.
Create database/collection
MongoDB creates database/collection lazily in common workflows, but explicit creation is useful for validators/options.
use course
db.createCollection("tasks")
Insert:
db.tasks.insertOne({
title: "Learn MongoDB",
completed: false,
createdAt: new Date()
})
Find
db.tasks.find()
Readable:
db.tasks.find({
completed: false
})
Do not confuse find() returning cursor with one in-memory array.
Cursors are covered in CRUD lesson.
Atlas
MongoDB Atlas is MongoDB's managed cloud service.
It can provide:
- managed clusters;
- backups;
- monitoring;
- search/vector features;
- network/security controls.
Do not expose Atlas to 0.0.0.0/0 with weak credentials in production just for convenience.
Use network access rules/private networking according to architecture.
Local Community Server
Local development options include:
- native install;
- Docker/container;
- local Atlas-related tooling where available.
Keep development data separate from production.
Connection string
Example:
mongodb://localhost:27017/course
Atlas commonly uses:
mongodb+srv://...
Connection string can include credentials.
Never commit it if secret-bearing.
Use environment/secret manager.
mongosh
Useful commands:
show dbs
show collections
db.getName()
db.tasks.findOne()
db.tasks.countDocuments()
Use shell for learning/admin diagnostics.
Production application uses driver.
MongoDB versus PostgreSQL
Choose MongoDB when data and access patterns fit document model.
Good candidates can include:
- content/catalog;
- nested aggregates;
- event/config documents;
- evolving polymorphic data;
- workloads benefiting from native sharding.
PostgreSQL may be better when:
- complex relational integrity;
- join-heavy normalized model;
- strict cross-entity transactions;
- complex SQL analytics;
- relational constraints dominate.
MongoDB supports transactions and joins ($lookup), but if every operation depends on many cross-document transactions/joins, relational model may be more natural.
Atomicity
MongoDB single-document write operations are atomic at document level.
This is one reason embedding data that changes together can reduce need for multi-document transactions.
Do not choose embedding solely for atomicity; document size/access patterns matter too.
Naming
Collections commonly plural:
users orders tasks
Field names:
- consistent;
- predictable;
- avoid unnecessary deeply nested paths;
- avoid dynamic user-controlled field names where possible.
MongoDB permits many characters/structures but not every schema is maintainable.
Schema validation preview
db.createCollection("tasks", {
validator: {
$jsonSchema: {
bsonType: "object",
required: [
"title",
"completed"
],
properties: {
title: {
bsonType: "string",
minLength: 3
},
completed: {
bsonType: "bool"
}
}
}
}
})
Database-level validation complements application validation.
Do not rely only on Mongoose if other writers can bypass it.
Common mistakes
- “NoSQL means no schema”;
- strings for dates/numbers;
- ObjectId treated as permission;
- unbounded arrays;
- huge files embedded in normal documents;
- Mongo chosen because JavaScript uses JSON;
- connection string committed;
- Atlas open to internet broadly;
- float for exact money without strategy;
- different types in same indexed field unintentionally.
Exercises
- Install/connect to MongoDB.
- Create tasks collection.
- Insert documents with Date/ObjectId.
- Compare string date versus Date queries.
- Store exact currency with two alternative strategies.
- Inspect BSON types.
- Add JSON schema validator.
- Model one SQL-like entity as a document and identify trade-offs.
- Decide Mongo vs PostgreSQL for five scenarios.
- Explain why ObjectId does not provide authorization.
Mastery checklist
Explain:
- MongoDB/document database;
- BSON/JSON;
- common BSON types;
- ObjectId;
- dates/money;
- collections/documents;
- flexible schema;
- Atlas/local;
- atomic document writes;
- use-case fit;
- document size/unbounded-array risks.
