MongoDB Intro
MongoDB is a document database. Records are JSON-like (BSON), schemas are flexible, and queries are JSON expressions. Sharding and replication are first-class.
MongoDB — what it is
EXAMPLE
// ===== The model =====
// - Database -> Collection -> Document (BSON)
// - Documents are JSON-like; can nest objects + arrays
// - Schema is enforced by the app, not the database (with optional schema validation)
// - Queries are JSON expressions evaluated server-side
// ===== Hello, collection =====
use shop;
db.orders.insertOne({
customer: { id: 'c-1', name: 'Alex Chen' },
total_cents: 4995,
lines: [{ sku: 'A-1', qty: 2 }, { sku: 'B-2', qty: 1 }],
tags: ['retail', 'shipped'],
created_at: new Date(),
});
// ===== Read =====
db.orders.findOne({ 'customer.id': 'c-1' });
db.orders.find({ total_cents: { $gte: 1000 } }).sort({ created_at: -1 }).limit(20);
// ===== Update =====
db.orders.updateOne(
{ _id: id },
{ $set: { 'customer.email': 'a@x.io' }, $push: { tags: 'vip' } }
);
// ===== Aggregate =====
db.orders.aggregate([
{ $match: { 'customer.id': 'c-1' } },
{ $group: { _id: null, total: { $sum: '$total_cents' }, n: { $sum: 1 } } },
]);
// ===== Indexes =====
db.orders.createIndex({ 'customer.id': 1, created_at: -1 });
db.orders.createIndex({ tags: 1 }); // multikey
db.orders.createIndex({ '$**': 'text' }); // full-text
// ===== Replica sets + sharding =====
// Replica set: primary + secondaries; secondaries serve reads with readPreference
// Sharded cluster: data partitioned by shard key across shards; mongos routes queries
// ===== When MongoDB wins =====
// - Variable / sparse document shapes
// - Hierarchical data that maps cleanly to JSON
// - Fast development iteration (no migrations for shape changes)
// - Geospatial / time series with built-in indexes
// ===== When MongoDB hurts =====
// - Strict relational integrity across many tables
// - Heavy multi-document transactions (supported but costlier than Postgres)
// - Reporting / BI workloads (use a warehouse or analytic store)
// ===== Patterns to internalise =====
// - Pre-aggregate documents to match read patterns (denormalise on purpose)
// - Index BEFORE you scale; explain() any new query
// - Schema validation when teams grow; collMod $jsonSchema
// - Use replica set readPreference for read scale; not as a sharding substitute
// ===== Pitfalls =====
// - Treating Mongo like Postgres (joins everywhere via $lookup)
// - Unbounded arrays inside documents -> 16MB cap, slow updates
// - No index on the query you run -> COLLSCAN
// - Reading from secondaries without understanding staleness
Why it matters
Mongo earns its keep when the data is documents and the schema actually varies. Index for the queries you run, denormalise on purpose, and reach for transactions sparingly. The mental model is "store the shape your app uses, optimise for the reads you make".
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
// MongoDB stores JSON-shaped documents in collections.
db.customers.insertOne({ name: 'Ada', age: 36 });
Try it Yourself »
Exercise
Insert a single document.
db.users.
({ name: 'Ada' });
camelCase; nine chars.
Discussion
Loading…