Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

MDB
MongoDB
0/10 completed
Beginner
What is MongoDB?Inserting and finding documentsUpdating and deleting
Intermediate
Query operatorsSorting, paging and projectionIndexes and explain()
Advanced
The aggregation pipelineJoins, facets and window functionsSchema design and validation
Pro
Drivers, transactions and scaling
Tracks / MongoDB / Pro

Drivers, transactions and scaling

You can model, query and aggregate data. This final lesson connects MongoDB to real applications and covers what happens at scale: multi-document transactions, replica sets, sharding and production practices.

Using MongoDB from code

Every major language has an official driver. The API mirrors what you've used in mongosh.

js
// Node.js: npm install mongodb
import { MongoClient, ObjectId } from 'mongodb';

const client = new MongoClient(process.env.MONGODB_URI);   // one client per app: it manages a connection pool
const db = client.db('shop');

export async function getProduct(id) {
  return db.collection('products').findOne({ _id: new ObjectId(id) });
}

export async function searchProducts({ category, maxPrice, page = 1 }) {
  return db.collection('products')
    .find({ category, price: { $lte: maxPrice } })
    .project({ name: 1, price: 1 })
    .sort({ price: 1 })
    .skip((page - 1) * 20)
    .limit(20)
    .toArray();
}
python
# Python: pip install pymongo
from pymongo import MongoClient

client = MongoClient(os.environ["MONGODB_URI"])
db = client.shop

for p in db.products.find({"price": {"$lt": 20}}).sort("price", 1):
    print(p["name"], p["price"])

Rules of thumb:

  • Create one client when the app starts and reuse it. Each client holds a connection pool; creating one per request exhausts connections.
  • Never build queries from raw user objects: find(req.body) lets an attacker send { "password": { "$ne": null } } (NoSQL injection). Validate input types first (e.g. with Zod), or use Mongoose's sanitizeFilter.
  • Keep credentials in environment variables or a secrets manager.

Single-document atomicity

Every write to one document is atomic, including nested fields and arrays. That's why good schema design (embedding things that change together) means you rarely need transactions:

MongoDB shell (simulated) · editable

The Monitor has 0 stock, so matchedCount: 0 and nothing changes, with no race condition.

Multi-document transactions

When a change must touch several documents atomically (a bank transfer between two account documents), use a transaction. Changes inside it are invisible to others until you commit, and an abort throws them all away:

MongoDB shell (simulated) · editable

And when something goes wrong, abort:

MongoDB shell (simulated) · editable

In application code, use the driver's withTransaction helper. It commits, and automatically retries on temporary errors:

js
const session = client.startSession();
try {
  await session.withTransaction(async () => {
    await accounts.updateOne({ _id: from }, { $inc: { balance: -amount } }, { session });
    await accounts.updateOne({ _id: to },   { $inc: { balance: amount } },  { session });
  });
} finally {
  await session.endSession();
}

Transactions need a replica set (Atlas always has one) and cost more than single-document writes. Keep them short and use them only where you need them.

Replica sets: high availability

Production MongoDB runs as a replica set: usually 3 servers holding copies of the same data.

          writes ─▶  PRIMARY  ──replicates──▶  SECONDARY
                         └──────replicates──▶  SECONDARY
  • All writes go to the primary; secondaries copy its operation log (oplog).
  • If the primary fails, the secondaries elect a new primary within seconds. Drivers reconnect automatically.
  • Write concern w: 'majority' (the default) means a write is confirmed only after most members have it, so it survives a failover.
  • Read preference can send reads to secondaries (secondaryPreferred) for analytics, at the cost of possibly slightly stale data.
MongoDB shell (simulated) · editable

Sharding: horizontal scale

When one replica set can't hold the data or handle the writes, sharding splits a collection across several replica sets (shards). A shard key decides where each document lives:

js
sh.shardCollection('shop.orders', { customerId: 'hashed' })

Choosing the shard key is the most important decision:

  • High cardinality (many distinct values) and even distribution of writes.
  • Queries should usually include the shard key, so they go to one shard instead of all of them.
  • ❌ A monotonically increasing key (like a timestamp) sends all new writes to one shard. Hash it, or use a compound key.

Most apps never need sharding. A well-indexed replica set handles a lot.

Change streams

Apps can subscribe to changes in real time, for notifications, cache invalidation or syncing to a search index:

js
const stream = db.collection('orders').watch([{ $match: { operationType: 'insert' } }]);
for await (const change of stream) {
  console.log('New order!', change.fullDocument.total);
}

Production checklist

  • Replica set (or Atlas) with w: 'majority'; automated backups with point-in-time restore, tested
  • Authentication on, least-privilege users per app, TLS, IP access lists (never expose port 27017 to the internet)
  • Indexes for every frequent query; no unexpected COLLSCANs (watch the slow-query log / Atlas Performance Advisor)
  • Schema validation on important collections
  • One MongoClient per process; sensible pool size and timeouts
  • Monitoring: opcounters, latency, replication lag, connections, disk and cache usage
  • Input validation against NoSQL injection

🎓 MongoDB track complete!

You can model data as documents, write CRUD operations and rich queries, design indexes with ESR and explain(), build aggregation pipelines with joins, facets and window functions, validate schemas, and understand transactions, replica sets and sharding.

Capstone project: an event ticketing API

  1. Collections: events (embedded venue, ticket types with prices and quantities), users, orders (referencing user and event, embedding a snapshot of ticket details), reviews.
  2. Validation: a $jsonSchema on events and orders.
  3. Buying tickets: decrement availability atomically with a conditional $inc, so you can never oversell, without a transaction.
  4. Refunds: use a transaction that updates the order and restores availability.
  5. Indexes: support "upcoming events in a city, sorted by date" (ESR), a unique email on users, and a TTL index on abandoned carts.
  6. Reports: revenue per event per month, top 5 events by tickets sold, and average rating per event with $lookup.
  7. Build it as a small Node.js or Python API using the official driver, and deploy it with MongoDB Atlas's free tier.
✎ Check your understanding

1.When do you need a multi-document transaction?

2.In a replica set, what happens when the primary fails?

3.Why is a timestamp a poor shard key by itself?

← Schema design and validation