MongoDB Tutorial with Examples.
MongoDB tutorial for document databases: aggregation pipelines, indexing, change streams and Atlas cloud patterns.
Beginner
Start here — no prior experience needed
Intermediate
For developers with core concepts down
Embedding vs Referencing: A 5.9MB Document and a 50x Fetch Time
Embed reviews inside a book document and push 50,000 of them in — the document balloons to 5.9MB and fetching it goes from 2ms to 102ms. Moving to a referenced collection brings the fetch back to 3ms.
explain() Proves It: 200,000 Docs Scanned vs. a Covered Query That Touches Zero
A query against 200,000 documents takes 65ms and scans every single one without an index. One index later it's 2ms. A covered query on top of that touches zero documents at all — explain() proves each claim.
The Aggregation Stage-Order Bug: Wrong Results, No Error
$limit before $sort doesn't error — it just silently returns the wrong documents. $match, $group, $sort, $limit, and $lookup, and the one ordering mistake that returns confidently wrong data.
When the Aggregation Optimizer Can (and Can't) Use Your Index
A $match placed after $group looks like it must scan everything first — but MongoDB's optimizer can rewrite it into a pure index lookup when filtering on the group key itself. Filter on a computed value like a $sum, and that optimization disappears entirely.
Change Streams: Watching a Collection in Real Time (Replica Set Required)
watch() fails outright on a standalone server — change streams need a replica set, even a local one. Once that's running: real insert/update/delete events, filtering by operation type, and resuming after a disconnect.
Multi-Document Transactions: When One Update Isn't Enough
Transfer money between two accounts as a single atomic transaction — then abort one on purpose and prove the balance actually rolls back, not just that the code stopped running.
Advanced
Production-grade patterns for experienced engineers
Killing the Primary and Measuring the Real Failover Time
docker kill the primary node of a real 3-node replica set and time exactly how long the cluster takes to elect a new one from container logs and MongoDB's own timestamps — 9.01 seconds, closely matching the documented default election timeout.
Sharding: Why 60,000 Fresh Documents Landed on Exactly One Shard
A real 2-shard cluster, a collection sharded from the start — and every one of 60,000 bulk-inserted documents lands on a single shard anyway, because a lone chunk under the size threshold has no reason to split or move.
The Profiler: Finding a Slow Query Without Knowing to Look for It
explain() answers 'is this specific query slow' — the profiler answers 'which of my queries are slow at all,' logging every operation over a threshold with its real execution stats, including the query plan, with no code changes needed.
Also part of MongoDB
Taught in other topics. Each link opens the lesson in its home topic.