MongoDB Roadmap

From your first document to running MongoDB in production: documents and BSON, the mongosh shell and CRUD, then data modeling, schema validation, indexes, explain plans and the aggregation pipeline, then drivers, transactions, change streams, full-text and vector search, and finally replica sets, sharding, security, backups and monitoring. 36 topics in four stages, each with what to learn, free resources, a practice task and, for most, an example you can paste into mongosh, a terminal or Python. Tick things off as you go; your progress is saved in this browser. Use the filter to follow the developer path, the DBA & operations path or the aggregation, search & AI path.

Written for MongoDB 9.0 (9.0.4, October 2026) and mongosh 2.14. Every shell example on this page was run against the official mongo:9.0 Docker image, and every link was checked in November 2026. Almost everything also works on MongoDB 7.0 and 8.0; the few 9.0-only features are marked.

The roadmap in detail

Everything from the map above, on one page. Dashed topics are optional. The hours are rough estimates for reading plus hands-on practice. Everything here runs for free on your own computer with Docker (or on a free Atlas cluster); one container is enough until stage 4, where you start a three-member replica set and a small sharded cluster.

Stage 1 · Beginner MongoDB and mongosh basics

MongoDB stores documents: JSON-like objects with nested fields and arrays, grouped into collections. Learn how documents and BSON types work, get fluent in the mongosh shell, and master create, read, update and delete. Every later topic builds on queries and update operators.

What MongoDB is and when to use it

MongoDB is a document database. Where a relational database splits an order into rows in orders, order_items and addresses, MongoDB usually stores the order as one document with the items and address nested inside it. Data that is read together is stored together, so most reads are a single lookup, and the shape of your data can change without a migration of every row.

A deployment holds databases, a database holds collections, and a collection holds documents. Documents in one collection don't have to share the same fields, although in practice they mostly do, and you can enforce a schema when you want one. MongoDB has secondary indexes, a powerful aggregation pipeline, multi-document ACID transactions, replication for high availability and sharding to spread data over many servers.

It fits well for product catalogues, user profiles, content management, IoT and event data, mobile back ends and anything whose data is naturally a tree of objects. It is a weaker fit when your data is highly relational with many-to-many joins in most queries, or when you need ad-hoc reporting across many entities (a relational database or a warehouse does that better). You will meet three flavours: the free Community Server, the paid Enterprise Advanced, and Atlas, MongoDB's managed cloud service with a free tier.

What to learn

  • Deployment → database → collection → document, and how that maps to SQL terms
  • Embedding related data versus splitting it into tables and joining
  • Flexible schema: what it gives you, and why you still design one
  • Good fits and poor fits for a document database
  • Community Server, Enterprise Advanced and Atlas: what each one is

Free resources

Practice

Take a small app you know (a blog, a shop, a to-do app). Sketch its data first as SQL tables, then as MongoDB documents. Which tables disappear because they become nested arrays? Which ones stay as separate collections, and why?

Prerequisites: JSON, a terminal, Docker and one language

MongoDB documents look like JSON, the shell speaks JavaScript, and you'll run the server in a container. Be comfortable reading JSON, using a terminal, starting containers and writing small programs in one language. The shell examples here are JavaScript; the app examples use Python because it reads easily, and the Node.js, Java, Go, C# and other drivers work the same way. Skip this topic if all of that is familiar.

What to learn

  • JSON: objects, arrays, strings, numbers, booleans and null
  • Just enough JavaScript for the shell: variables, objects, arrays, functions and loops
  • Terminal basics and environment variables
  • Docker: images, containers, published ports and named volumes
  • One programming language well enough to install a package and write a small script

Free resources

Practice

Write a JSON file describing three books with nested authors and an array of tags. Check it in a JSON formatter, then write a short script in your language that loads it and prints every tag only once.

Install MongoDB: Docker, Atlas and Compass

The quickest start is the official mongo Docker image: it contains the server (mongod), the shell (mongosh) and the database tools. Start it as a single-member replica set from day one: it costs nothing extra, and transactions and change streams (stage 3) only work on a replica set. If you'd rather not run anything locally, create a free Atlas M0 cluster in the browser. Compass is the free desktop GUI for browsing documents, building queries and aggregations, and reading explain plans.

# start MongoDB 9.0 as a one-member replica set called rs0
docker run -d --name mongo -p 27017:27017 \
  -v mongo-data:/data/db mongo:9.0 --replSet rs0

# initialise the replica set once (then it remembers)
docker exec mongo mongosh --quiet --eval \
  'rs.initiate({_id: "rs0", members: [{_id: 0, host: "localhost:27017"}]})'

# open the shell
docker exec -it mongo mongosh

Apps on your computer then connect with mongodb://localhost:27017/?replicaSet=rs0. The data lives in the mongo-data volume, so it survives removing the container.

What to learn

  • Run MongoDB in Docker with a named volume, and publish the port only on your own machine
  • Initialise a single-member replica set and check it with rs.status()
  • Create a free Atlas M0 cluster, a database user and an IP access list entry
  • Read a connection string: mongodb:// versus mongodb+srv://, options after the ?
  • Connect Compass and browse a collection

Free resources

Practice

Start MongoDB with the commands above, insert one document from mongosh, remove the container (docker rm -f mongo), start it again with the same volume and check the document is still there. Then create a free Atlas cluster and connect to it from both mongosh and Compass.

The MongoDB Shell (mongosh)

mongosh is a full Node.js-based JavaScript REPL connected to your deployment. It replaced the old mongo shell, which was removed in MongoDB 6.0, so ignore tutorials that type mongo. You'll live in it: exploring data, trying queries before putting them in code, creating indexes and users, and checking a server's health.

// connect: mongosh "mongodb://localhost:27017/?replicaSet=rs0"
show dbs                    // list databases
use shop                    // switch (created on first write)
db.getName()                // → shop
show collections            // list collections in shop
db.products.insertOne({ name: "Desk lamp", price: 24.5 })
db.products.findOne()       // → { _id: ObjectId('…'), name: … }
db.version()                // → 9.0.4
db.products.help()          // methods you can call on a collection
const cheap = db.products.find({ price: { $lt: 30 } }).toArray()
cheap.length                // → 1 (it's JavaScript: use variables)

What to learn

  • Connect with a connection string, and with --username plus a password prompt
  • Helpers: show dbs, use, show collections, db, help and tab completion
  • Use JavaScript in the shell: variables, loops, printjson(), .toArray()
  • Iterate a cursor: it for the next batch, config.set("displayBatchSize", 50)
  • Edit long commands with edit and search history with Ctrl+R

Free resources

Practice

In mongosh, use a JavaScript for loop to insert 100 documents { n: i, even: i % 2 === 0 } into a numbers collection. Count the even ones, print the first five as JSON, then drop the collection. Do it once typing line by line and once with edit.

Documents, BSON types and ObjectId

MongoDB stores documents as BSON, a binary form of JSON with more types: 32- and 64-bit integers, doubles, Decimal128 for money, real dates, binary data and ObjectId. Every document has an _id that is unique in its collection; if you don't set one, the driver creates an ObjectId, which starts with its creation time in seconds. A single document can be at most 16 MB.

use shop
db.types.insertOne({
  _id: 10,
  qty: NumberInt(5),                     // 32-bit int
  views: NumberLong("9007199254740993"), // 64-bit int
  price: NumberDecimal("0.10"),          // exact decimal
  when: ISODate("2026-11-05T10:00:00Z")  // a real date
})
db.types.findOne({ _id: 10 })
// → { _id: 10, qty: 5, views: Long('9007199254740993'),
//     price: Decimal128('0.10'),
//     when: ISODate('2026-11-05T10:00:00.000Z') }
db.types.countDocuments({ qty: { $type: "int" } })    // → 1
ObjectId("6720f1a2c3b4d5e6f7a8b9c0").getTimestamp()
// → ISODate('2024-10-29T14:30:58.000Z')

What to learn

  • BSON types: string, int, long, double, Decimal128, bool, date, null, ObjectId, binary, array, object
  • Why money belongs in Decimal128 (or integer cents), never in a double
  • Dates as BSON dates in UTC, not as strings
  • _id rules, ObjectId structure, and choosing your own _id
  • Field name rules, the 16 MB document limit and Extended JSON

Free resources

Practice

Insert an order with a total of 0.1 + 0.2 as a double and another as NumberDecimal("0.3"). Query for orders whose total equals 0.3 and explain the result. Then pull the creation time out of three ObjectIds and convert them with the timestamp converter.

Create: inserting documents

insertOne() adds one document and insertMany() adds a batch. Collections and databases are created on the first insert. A duplicate _id (or any unique-index clash) fails that document; with insertMany the default is ordered, so it stops at the first error, while { ordered: false } carries on and reports every failure at the end.

use shop
db.products.drop()
db.products.insertOne({ _id: 1, name: "Desk lamp", price: 24.5,
  tags: ["home", "light"], stock: 12 })
// → { acknowledged: true, insertedId: 1 }
db.products.insertMany([
  { _id: 2, name: "Office chair", price: 149,
    tags: ["home", "office"], stock: 3 },
  { _id: 3, name: "USB-C cable", price: 9.99, tags: ["tech"],
    stock: 250 },
  { _id: 4, name: "Monitor arm", price: 59,
    tags: ["office", "tech"], stock: 0 }
])
// → { acknowledged: true, insertedIds: { '0': 2, '1': 3, '2': 4 } }

What to learn

  • insertOne and insertMany, and the result they return
  • Ordered versus unordered bulk inserts and duplicate key errors (E11000)
  • When the driver adds _id, and why you may want natural keys
  • bulkWrite() for a mix of inserts, updates and deletes in one round trip
  • Loading test data with mongoimport or a script

Free resources

Practice

Generate 1,000 fake customers with the fake data generator, save them as JSON and insert them with insertMany. Then insert a batch of five where the third has a duplicate _id, once ordered and once unordered, and compare how many documents went in.

Read: queries, projection and cursors

find(filter, projection) returns a cursor over matching documents; findOne() returns the first match. The filter is itself a document: { stock: 0 } means equality, and operators such as $gt, $in, $or, $exists and $regex do the rest. A projection picks the fields to return, and sort(), skip() and limit() shape the cursor.

use shop
db.products.find(
  { price: { $lt: 60 }, stock: { $gt: 0 } },  // AND of two conditions
  { name: 1, price: 1, _id: 0 }               // projection
).sort({ price: 1 })
// → [ { name: 'USB-C cable', price: 9.99 },
//     { name: 'Desk lamp', price: 24.5 } ]
db.products.countDocuments({ tags: "office" })  // → 2
db.products.find({ $or: [{ stock: 0 }, { price: { $gte: 100 } }] },
  { name: 1 })
// → [ { _id: 2, name: 'Office chair' },
//     { _id: 4, name: 'Monitor arm' } ]
db.products.find({ name: /^desk/i }, { _id: 1 })  // → [ { _id: 1 } ]
db.products.distinct("tags")
// → [ 'home', 'light', 'office', 'tech' ]

What to learn

  • Equality, comparison ($eq $ne $gt $gte $lt $lte $in $nin) and logical operators ($and $or $not $nor)
  • $exists, $type, $regex and the difference between a missing field and null
  • Projections: include, exclude, and why you can't mix them (except _id)
  • Cursors: sort, limit, skip, and why deep skip pagination gets slow
  • countDocuments, estimatedDocumentCount and distinct

Free resources

Practice

Using your 1,000 customers: find customers from two countries who signed up this year, show only name and email, sorted by signup date, 20 per page. Write page 3 with skip, then rewrite it as "range" pagination ({ signedUp: { $gt: lastSeen } }) and explain why that scales better.

Update and delete

Updates use update operators that change fields in place: $set, $unset, $inc, $push, $pull, $addToSet and more. Each single-document update is atomic, so $inc never loses a count even with many app servers. An upsert inserts when nothing matches. findOneAndUpdate() changes a document and returns it in one step, which is how you claim a job or reserve stock safely.

use shop
db.products.updateOne({ _id: 2 },
  { $inc: { stock: -1 }, $set: { onSale: true } })
// → { matchedCount: 1, modifiedCount: 1, upsertedCount: 0, … }
db.products.updateOne({ _id: 9 },
  { $set: { name: "Webcam", price: 39, stock: 5 } },
  { upsert: true })
// → { insertedId: 9, matchedCount: 0, upsertedCount: 1, … }
// take 2 cables only if at least 2 are left, and return the result
db.products.findOneAndUpdate(
  { _id: 3, stock: { $gte: 2 } },
  { $inc: { stock: -2 } },
  { returnDocument: "after", projection: { stock: 1 } })
// → { _id: 3, stock: 248 }
db.products.updateMany({}, { $unset: { onSale: "" } })
db.products.deleteMany({ stock: 0 })
// → { acknowledged: true, deletedCount: 1 }

What to learn

  • updateOne, updateMany and replaceOne, and what each one changes
  • Field operators: $set $unset $inc $mul $min $max $rename $currentDate
  • Upserts, and the race you avoid by putting the condition in the filter
  • findOneAndUpdate / findOneAndDelete with returnDocument
  • deleteOne, deleteMany, and dropping a whole collection instead

Free resources

Practice

Build a page-view counter: one document per page, created by the first view with an upsert, $inc on every view, and $currentDate for the last view time. Run 20 parallel mongosh --eval loops of 100 increments each and check the final count is exactly 2,000.

Arrays and nested documents

Nested fields are reached with dot notation ("address.city"). A query on an array field matches if any element matches, which is handy and also the source of the classic bug: two conditions on an array of objects may be met by two different elements unless you use $elemMatch. To change one element, use the positional $, $[] for all elements, or $[name] with arrayFilters.

use shop
db.orders.drop()
db.orders.insertOne({ _id: 1, customer: { name: "Asha",
    city: "Pune" },
  items: [ { sku: "lamp", qty: 1, price: 24.5 },
           { sku: "cable", qty: 3, price: 9.99 } ] })
db.orders.countDocuments({ "customer.city": "Pune" })        // → 1
// any item with qty 3, and (maybe another) item with price 24.5
db.orders.countDocuments({ "items.qty": 3,
  "items.price": 24.5 })                                     // → 1
// one item with BOTH qty 3 and price 24.5
db.orders.countDocuments({ items: { $elemMatch:
  { qty: 3, price: 24.5 } } })                               // → 0
db.orders.updateOne({ _id: 1, "items.sku": "cable" },
  { $inc: { "items.$.qty": 1 } })          // positional $
db.orders.updateOne({ _id: 1 },
  { $push: { items: { sku: "arm", qty: 1, price: 59 } } })
db.orders.findOne({ _id: 1 }, { "items.sku": 1, "items.qty": 1 })
// → { _id: 1, items: [ { sku: 'lamp', qty: 1 },
//     { sku: 'cable', qty: 4 }, { sku: 'arm', qty: 1 } ] }

What to learn

  • Dot notation for nested fields and for array positions ("items.0.sku")
  • Array queries: any-element matching, $all, $size and $elemMatch
  • Array updates: $push (with $each, $slice, $sort), $pull, $addToSet, $pop
  • Positional $, all-positional $[] and filtered $[x] with arrayFilters
  • Why arrays that grow without limit are a design smell

Free resources

Practice

Model a blog post with an array of comments, each with an author, text and likes. Add a comment, like one comment by its id, delete one comment, keep only the 50 newest comments with $push + $slice, and find posts where a single comment by "ravi" has more than 10 likes.

Am I ready? Stage 1 quiz

Ten app servers each read a product's stock, subtract one in code and write it back. Stock goes wrong under load. What's the fix?

  1. Use replaceOne instead of updateOne
  2. Read the document twice before writing
  3. Use updateOne({ _id, stock: { $gt: 0 } }, { $inc: { stock: -1 } }), a single atomic update
  4. Add an index on stock

Two servers can both read 5 and write 4. A single update with $inc is atomic, and putting the condition in the filter stops stock going below zero.

Orders have items: [{ sku, qty }]. Which query finds orders where one item has sku "lamp" and qty greater than 2?

  1. { items: { $elemMatch: { sku: "lamp", qty: { $gt: 2 } } } }
  2. { "items.sku": "lamp", "items.qty": { $gt: 2 } }
  3. { items: { sku: "lamp", qty: { $gt: 2 } } }
  4. { $and: [{ items: "lamp" }, { items: { $gt: 2 } }] }

Option 2 can match a lamp with qty 1 plus a different item with qty 5. Option 3 is an exact match on a whole embedded document. $elemMatch applies both conditions to the same element.

What's the best type for a product price?

  1. A string such as "24.50"
  2. A double
  3. A date
  4. Decimal128 (or an integer number of cents)

Doubles can't hold 0.1 exactly, so sums drift. Decimal128 is exact, and integer cents are a common alternative. Strings can't be summed or compared numerically.

You run db.products.find({}, { name: 1, price: 0 }). What happens?

  1. You get name only
  2. An error: you can't mix inclusion and exclusion (except for _id)
  3. You get every field except price
  4. You get price only

A projection either lists the fields to include or the fields to exclude. The only field you may exclude in an inclusion projection is _id.

An old tutorial tells you to type mongo to open the shell, and it isn't found. Why?

  1. You need to install it with npm
  2. It only works on Atlas
  3. The legacy mongo shell was removed in MongoDB 6.0; use mongosh
  4. It was renamed to mongod

mongosh is the current shell. mongod is the server process itself.

Stage 2 · Beginner → Intermediate Modeling, indexes and aggregation

This is where MongoDB skill really lives. A good schema and the right indexes make most performance problems disappear before they start, and the aggregation pipeline replaces a lot of application code. You'll also connect from a real program and learn the command-line tools that ship with MongoDB.

Data modeling: embed or reference

The golden rule is "data that is accessed together should be stored together". Start from your application's queries, not from entities. Embed when the child belongs to one parent, is read with it and stays bounded in size (an order's line items, a user's addresses). Reference by _id when the child is shared, large, unbounded or read on its own (an author of many books, a product in many orders). Duplicating a little data that rarely changes, such as a product name inside an order, is normal and often wise.

// embedded: one read returns the whole order
{ _id: 1001, customerId: 7, status: "paid",
  shipTo: { city: "Pune", pin: "411001" },
  items: [ { productId: 1, name: "Desk lamp", qty: 1,
             price: NumberDecimal("24.50") } ] }

// referenced: reviews are unbounded, so they get a collection
{ _id: ObjectId("…"), productId: 1, userId: 7, stars: 5,
  text: "Bright and sturdy" }

What to learn

  • Design from the workload: list the queries, their frequency and their read/write ratio
  • One-to-one, one-to-few, one-to-many and one-to-squillions, and how each is modeled
  • Many-to-many with arrays of references on one or both sides
  • When duplication is fine, and how you update duplicated fields
  • Anti-patterns: unbounded arrays, too many collections, bloated documents, needless $lookup

Free resources

Practice

Design the collections for a food-delivery app: restaurants, menus, customers, orders, reviews and live rider locations. For each one write its top three queries, then decide embed or reference and justify it in one line. Mark every field you chose to duplicate and how it gets updated.

Schema design patterns

MongoDB's design patterns are named answers to common problems. The computed pattern stores a running total instead of recomputing it on every read. The subset pattern keeps the 10 newest reviews inside the product and the rest in their own collection. The extended reference copies the few fields you always show (a customer's name in an order). The bucket pattern groups many small readings into one document per hour. Outlier, polymorphic, attribute, approximation and schema versioning complete the usual list.

What to learn

  • Computed and approximation patterns for counters and totals
  • Subset and extended reference patterns to keep hot documents small
  • Bucket pattern for time-based data (and when time series collections replace it)
  • Polymorphic and attribute patterns for products with different fields
  • Outlier and schema versioning patterns, and migrating documents lazily

Free resources

Practice

Take your food-delivery design and apply three patterns: a computed average rating on each restaurant, a subset of the five latest reviews, and buckets of rider locations per rider per minute. Add a schemaVersion field and write a script that upgrades version 1 documents to version 2.

Schema validation

A flexible schema doesn't mean no schema. Attach a $jsonSchema validator to a collection and the server rejects documents that don't fit, whichever app or script wrote them. validationAction: "warn" only logs, which is how you add rules to an existing collection safely. MongoDB 9.0 adds the constraint validation level, which also guarantees every existing document passes the rules.

use shop
db.createCollection("customers", { validator: { $jsonSchema: {
  bsonType: "object",
  required: ["email", "name"],
  properties: {
    email: { bsonType: "string", pattern: "^.+@.+$" },
    name:  { bsonType: "string", minLength: 1 },
    plan:  { enum: ["free", "pro"] }
  } } } })
db.customers.insertOne({ name: "Ravi", email: "ravi@example.com",
  plan: "pro" })                  // ok
db.customers.insertOne({ name: "Bad", plan: "gold" })
// → MongoServerError: Document failed validation
//   (details list the missing "email" and the bad "plan")

What to learn

  • $jsonSchema: bsonType, required, properties, enum, pattern, min/max
  • validationLevel (strict, moderate, and constraint in 9.0) and validationAction (error or warn)
  • Add or change a validator on an existing collection with collMod
  • Read the detailed validation error to see which rule failed
  • Find existing documents that break the rules with $jsonSchema in a query

Free resources

Practice

Add a validator to your 1,000-customer collection in warn mode first. Find the documents that would fail, fix them with updateMany, then switch to error. Try inserting five bad documents and read each error.

Indexes

Without an index, MongoDB reads every document in the collection (a COLLSCAN). An index is a sorted B-tree of field values pointing to documents. Compound indexes are the workhorse; order their fields by the ESR rule: Equality fields first, then Sort fields, then Range fields. Indexes on arrays become multikey automatically. Every index speeds reads up and slows writes down a little, so index for your real queries.

use shop
db.orders.drop()
for (let i = 0; i < 5000; i++) {
  db.orders.insertOne({ customerId: i % 100,
    status: i % 3 ? "paid" : "new",
    total: i % 500, createdAt: new Date(2026, 0, 1 + (i % 300)) })
}
// ESR: equality (customerId, status), sort (createdAt), range (total)
db.orders.createIndex({ customerId: 1, status: 1, createdAt: -1,
  total: 1 })
db.users.createIndex({ email: 1 }, { unique: true })
db.sessions.createIndex({ lastSeen: 1 },
  { expireAfterSeconds: 3600 })        // TTL: deleted after 1 h
db.orders.createIndex({ createdAt: 1 },
  { partialFilterExpression: { status: "new" } })
db.orders.getIndexes().length          // → 3

What to learn

  • Single-field and compound indexes, and the ESR rule for field order
  • Index prefixes: which queries can use { a: 1, b: 1, c: 1 }
  • Multikey, unique, partial, sparse, TTL, hashed and wildcard indexes
  • Index builds on a live system, hiding an index before dropping it
  • The cost of indexes: write speed, RAM, and finding unused ones with $indexStats

Free resources

Practice

Load 100,000 orders. Write the five queries an order-history page needs (by customer, by status, newest first, by date range, a total above X). Design the fewest indexes that serve all five, check each with explain, and measure insert speed before and after adding them.

Query plans with explain()

explain("executionStats") shows how a query actually ran: the winning plan (IXSCAN, COLLSCAN, FETCH, SORT), and how many index keys and documents were examined compared with how many were returned. A healthy query examines about as many documents as it returns. A SORT stage means the sort happened in memory; a covered query is answered from the index alone, with zero documents examined.

use shop
const q = { customerId: 7, status: "paid" }
const ex = db.orders.find(q).sort({ createdAt: -1 }).explain(
  "executionStats")
ex.executionStats.nReturned                     // → 34
ex.executionStats.totalKeysExamined             // → 34
ex.executionStats.totalDocsExamined             // → 34
// covered: only indexed fields, and _id excluded
const cov = db.orders.find(q, { _id: 0, createdAt: 1 }).explain(
  "executionStats")
cov.executionStats.totalDocsExamined            // → 0
const scan = db.orders.find({ total: 10 }).explain("executionStats")
scan.executionStats.totalDocsExamined           // → 5000 (COLLSCAN)

What to learn

  • The three verbosity modes: queryPlanner, executionStats, allPlansExecution
  • Read the stages: COLLSCAN, IXSCAN, FETCH, SORT, PROJECTION_COVERED
  • Compare nReturned, totalKeysExamined and totalDocsExamined
  • Covered queries, in-memory sorts and the plan cache
  • Use Compass's explain view and, on Atlas, the Performance Advisor

Free resources

Practice

Take your five order-history queries and record nReturned, keys examined, docs examined and time for each, with and without your indexes. Make one of them covered. Then swap the field order in one compound index and show with explain how it gets worse.

The aggregation pipeline

An aggregation pipeline is a list of stages that documents flow through, each stage transforming the stream: $match filters, $group groups and sums, $project / $set reshape, $sort, $limit, $unwind splits an array into one document per element, and $count counts. Put $match and $sort early so they can use indexes and shrink the stream.

use shop
db.sales.drop()
db.sales.insertMany([
  { region: "north", product: "lamp", qty: 3, price: 25 },
  { region: "north", product: "chair", qty: 1, price: 149 },
  { region: "south", product: "lamp", qty: 5, price: 25 },
  { region: "south", product: "cable", qty: 10, price: 10 }
])
db.sales.aggregate([
  { $match: { qty: { $gte: 2 } } },
  { $group: { _id: "$region",
      revenue: { $sum: { $multiply: ["$qty", "$price"] } },
      orders: { $sum: 1 } } },
  { $sort: { revenue: -1 } }
])
// → [ { _id: 'south', revenue: 225, orders: 2 },
//     { _id: 'north', revenue: 75, orders: 1 } ]

What to learn

  • Core stages: $match $project $set $unset $group $sort $limit $skip $count $unwind
  • Accumulators: $sum $avg $min $max $first $last $push $addToSet
  • Expressions: "$field" paths, arithmetic, $cond, $ifNull, string and date operators
  • Stage order and index use; memory limits and allowDiskUse
  • Build and debug pipelines stage by stage in Compass

Free resources

Practice

On your 100,000 orders: revenue per month, the top 10 customers by spend, average order value per status, and the number of orders per weekday. Write each pipeline in Compass one stage at a time, then copy it into a script.

Advanced aggregation: $lookup, $facet and window functions

$lookup joins documents from another collection (use it for occasional reads, not as the basis of every query). $facet runs several sub-pipelines over the same input, which is how search pages get results and filter counts in one call. $bucket builds histograms, $setWindowFields gives running totals and rankings like SQL window functions, and $merge / $out write results into a collection for materialized views.

use shop
db.customers.drop()
db.customers.insertMany([ { _id: 1, name: "Asha" },
                          { _id: 2, name: "Ravi" } ])
db.invoices.drop()
db.invoices.insertMany([ { customerId: 1, amount: 40, day: 1 },
  { customerId: 1, amount: 60, day: 2 },
  { customerId: 2, amount: 25, day: 1 } ])
db.invoices.aggregate([
  { $group: { _id: "$customerId", total: { $sum: "$amount" } } },
  { $lookup: { from: "customers", localField: "_id",
      foreignField: "_id", as: "customer" } },
  { $project: { _id: 0, total: 1,
      name: { $first: "$customer.name" } } },
  { $sort: { total: -1 } }
])
// → [ { total: 100, name: 'Asha' }, { total: 25, name: 'Ravi' } ]
db.invoices.aggregate([ { $setWindowFields: {
    partitionBy: "$customerId", sortBy: { day: 1 },
    output: { running: { $sum: "$amount",
      window: { documents: ["unbounded", "current"] } } } } },
  { $match: { customerId: 1 } },
  { $project: { _id: 0, day: 1, running: 1 } } ])
// → [ { day: 1, running: 40 }, { day: 2, running: 100 } ]

What to learn

  • $lookup (simple and with a pipeline), and why it needs an index on the foreign field
  • $facet, $bucket and $bucketAuto for search pages and histograms
  • $setWindowFields for running totals, moving averages and ranks
  • $merge and $out for materialized views; views with createView
  • Array expressions: $filter, $map, $reduce

Free resources

Practice

Build a product search response with $facet: page 1 of results, counts per category and a price histogram, all from one pipeline. Then write a nightly $merge pipeline that keeps a daily_sales collection up to date and only touches the last two days.

Drivers: MongoDB from your code

Official drivers exist for Python (PyMongo, with an async API), Node.js, Java, C#/.NET, Go, Rust, PHP, Ruby, Kotlin, Swift, C and C++. They all share one specification, so the ideas carry over: create one client per process (it holds a connection pool and watches the replica set), read the connection string from configuration, and let the driver retry reads and writes once after a failover.

import os
from pymongo import MongoClient

# One client per process: it keeps a pool and follows failovers.
uri = os.environ.get("MONGODB_URI",
                     "mongodb://localhost:27017/?replicaSet=rs0")
client = MongoClient(uri, serverSelectionTimeoutMS=3000)
products = client.shop.products

products.update_one({"_id": 100},
                    {"$set": {"name": "Notebook", "price": 3.5}},
                    upsert=True)
doc = products.find_one({"_id": 100}, {"_id": 0})
print(doc)                       # {'name': 'Notebook', 'price': 3.5}
for p in products.find({"price": {"$lt": 10}}).sort("price", 1):
    print(p["name"])

What to learn

  • Install the driver for your language and connect with a URI from an environment variable
  • The client lifecycle: one client, connection pool size, timeouts
  • CRUD, cursors and aggregation from code; mapping BSON types to your language
  • Retryable reads and writes, and handling duplicate key and network errors
  • The async API for async frameworks (PyMongo async, the Node.js driver)

Free resources

Practice

Build a small REST API for products (list with paging, get, create, update stock, delete) in any framework, with the URI in an environment variable. Return 404 for a missing id and 409 for a duplicate. Stop the container while it runs and make sure requests fail within a few seconds and recover on their own.

ODMs: Mongoose and friends

An ODM (object-document mapper) adds schemas, validation, defaults and hooks in your application code. Mongoose is the standard for Node.js; Python has Beanie and MongoEngine, Java has Spring Data MongoDB, and .NET has the EF Core provider. They speed up CRUD apps, but they hide what queries run, so learn the plain driver first and turn on query logging when you use one.

What to learn

  • Define a schema and model, with validation and defaults
  • populate() and why it can turn into many queries
  • Middleware (hooks), virtuals and lean queries
  • How the ODM's indexes are created, and why not to sync them on every start
  • Turning on debug logging to see the real queries

Free resources

Practice

Rebuild your products API with an ODM. Turn on debug logging, load a page that lists 20 products with their category through populate() (or the equivalent), count the queries, and rewrite it so it uses two queries at most.

Scripting and automating with mongosh

mongosh isn't only interactive. --eval runs one command, --file (or load()) runs a script, and --json prints machine-readable output for other tools, so it fits into shell scripts, cron jobs and CI. A ~/.mongoshrc.js file runs at start-up for your own helpers, config.set() changes shell settings, and snippets install shared helper packages.

# one-off command, JSON output, exit code for scripts
mongosh "mongodb://localhost:27017/shop" --quiet --json=relaxed \
  --eval 'db.products.countDocuments({ stock: { $lt: 5 } })'

# run a script file against a database
mongosh "mongodb://localhost:27017/shop" --quiet --file report.js

# in ~/.mongoshrc.js (the interactive shell loads it)
#   globalThis.lowStock = (n = 5) =>
#     db.products.find({ stock: { $lt: n } }, { name: 1 }).toArray()

What to learn

  • --eval, --file, --quiet, --json and exit codes
  • Writing scripts: db.getSiblingDB(), print(), printjson(), EJSON.stringify()
  • .mongoshrc.js, config.set() and a custom prompt
  • Reading environment variables in scripts with process.env
  • Never putting passwords on the command line (use a prompt or a config file)

Free resources

Practice

Write report.js that prints yesterday's order count and revenue as JSON. Run it from a shell script that exits with code 1 if revenue is zero, and schedule it daily with cron. Add a lowStock() helper to your .mongoshrc.js.

Database tools: mongoimport, mongodump and friends

The MongoDB Database Tools are separate command-line programs (included in the Docker image). mongoimport and mongoexport move JSON and CSV in and out; mongodump and mongorestore make and restore binary BSON backups of databases or collections; mongostat and mongotop show live activity; bsondump reads BSON files; mongofiles works with GridFS.

# import a CSV with a header row, then export as JSON lines
mongoimport --uri "mongodb://localhost:27017/shop" \
  --collection people --type csv --headerline --file people.csv
mongoexport --uri "mongodb://localhost:27017/shop" \
  --collection people --query '{"city": "Pune"}' --out pune.json

# back up one database (compressed archive) and restore it elsewhere
mongodump --uri "mongodb://localhost:27017" --db shop \
  --gzip --archive=shop.gz
mongorestore --uri "mongodb://localhost:27017" --gzip \
  --archive=shop.gz --nsFrom 'shop.*' --nsTo 'shop_copy.*'

mongostat --uri "mongodb://localhost:27017" -n 3  # 3 rows of stats

What to learn

  • mongoimport / mongoexport for JSON, JSON lines and CSV, with field types
  • mongodump / mongorestore: archives, gzip, one collection, renaming namespaces
  • Why mongoexport isn't a backup (it loses some BSON type detail)
  • mongostat and mongotop for a quick live view
  • Installing the tools on their own, outside Docker

Free resources

Practice

Export a spreadsheet as CSV, import it with proper types, fix a few rows in mongosh, and export the result as JSON. Then dump the whole shop database to a gzip archive, drop it, restore it, and check the document counts match.

Am I ready? Stage 2 quiz

A query filters on status (equality), sorts by createdAt and filters total > 100. Which index follows the ESR rule?

  1. { total: 1, createdAt: -1, status: 1 }
  2. { status: 1, createdAt: -1, total: 1 }
  3. { createdAt: -1, total: 1, status: 1 }
  4. Three single-field indexes

Equality first, then sort, then range. With the range field before the sort field, MongoDB has to sort in memory.

Each product can have thousands of reviews and the product page shows the newest 10. What's the best model?

  1. Embed every review in the product
  2. One collection per product
  3. Store reviews only in a SQL database
  4. Reviews in their own collection, plus the 10 newest embedded in the product (subset pattern)

Embedding them all makes an unbounded array that bloats the document. The subset pattern keeps the page to one read and the document small.

explain() shows nReturned: 20 and totalDocsExamined: 480000. What does it tell you?

  1. The query reads far more documents than it needs: it's missing a good index
  2. The query is covered
  3. The query is perfect
  4. The result was cached

A healthy query examines about as many documents as it returns. This one probably did a collection scan.

Which pipeline order is usually best?

  1. $group, then $match, then $sort
  2. $project every field first, then $match
  3. $match and $sort first, then $group
  4. Order doesn't matter

Early $match and $sort can use indexes and shrink the data every later stage processes.

Where should your app create the MongoClient?

  1. Once per request, and close it afterwards
  2. Once per process, shared by the whole app
  3. Once per query
  4. Once per collection

The client holds a connection pool and monitors the deployment. Creating one per request is slow and can exhaust the server's connections.

Stage 3 · Intermediate Building real applications

Real apps need guarantees: several documents changed together or not at all, writes that survive a server failing, and reactions to changes as they happen. Then come the specialised features that save you from running a second system: geospatial queries, time series, full-text search and vector search for AI apps.

Multi-document transactions

A single-document update is always atomic, which is why good modeling makes transactions rare. When you must change several documents together (move money between two accounts, place an order and reserve stock), use a multi-document ACID transaction inside a session. Transactions need a replica set or sharded cluster, should stay short (the default limit is 60 seconds), and should be retried as a whole on a TransientTransactionError, which the drivers' withTransaction helpers do for you.

use bank
db.accounts.drop()
db.accounts.insertMany([ { _id: "asha", balance: 100 },
                         { _id: "ravi", balance: 20 } ])
const session = db.getMongo().startSession()
const acc = session.getDatabase("bank").accounts
session.withTransaction(() => {
  const r = acc.updateOne({ _id: "asha", balance: { $gte: 30 } },
                          { $inc: { balance: -30 } })
  if (r.modifiedCount !== 1) throw new Error("not enough money")
  acc.updateOne({ _id: "ravi" }, { $inc: { balance: 30 } })
})
session.endSession()
db.accounts.find().toArray()
// → [ { _id: 'asha', balance: 70 }, { _id: 'ravi', balance: 50 } ]

What to learn

  • When you need a transaction, and when a single-document update or a better model is enough
  • Sessions, startTransaction / commitTransaction / abortTransaction
  • The callback API (withTransaction) and automatic retries
  • Limits: time, size, and the cost of long transactions on a busy server
  • Read and write concern inside a transaction

Free resources

Practice

Implement "place order" in your API: insert the order and decrement stock for every item in one transaction, failing the whole order if any item is out of stock. Fire 50 concurrent orders at the last 10 units with the load tester and check exactly 10 succeed and stock ends at zero.

Write concern, read concern and read preference

These three settings decide how safe and how fresh your data is. Write concern says how many members must confirm a write: w: "majority" (the default) means it survives the primary failing. Read concern says how durable the data you read must be ("local", "majority", "snapshot"). Read preference chooses which member serves reads; reading from secondaries can return slightly stale data, so it's for analytics or geography, not for read-your-own-writes.

use shop
db.payments.insertOne({ orderId: 1001, amount: 49 },
  { writeConcern: { w: "majority", wtimeout: 5000 } })
db.payments.find({ orderId: 1001 }).readConcern("majority").readPref(
  "primaryPreferred").toArray().length           // → 1
// connection string form for an app:
// mongodb://h1,h2,h3/?replicaSet=rs0&w=majority
//   &readPreference=secondaryPreferred&maxStalenessSeconds=120

What to learn

  • Write concern: w: 1, w: "majority", j: true and wtimeout
  • Read concern levels and what "majority committed" means
  • Read preference modes, tags and maxStalenessSeconds
  • Causal consistency sessions for read-your-own-writes on secondaries
  • Which setting to use for payments, product pages and dashboards

Free resources

Practice

On a three-member replica set (stage 4), pause one secondary with docker pause, write with w: 3 and a 2-second wtimeout, and read the error. Then write with w: "majority" and see it succeed. Read from the paused member's sibling with secondary preference and explain what you see.

Change streams

A change stream lets your app subscribe to inserts, updates, deletes and more on a collection, a database or the whole deployment, in order, as they happen. Each event carries a resume token, so a worker that restarts carries on where it stopped. Use them to invalidate caches, push live updates to browsers, sync to a search engine or publish events to Kafka. They need a replica set.

use shop
const cs = db.products.watch([
  { $match: { operationType: { $in: ["insert", "update"] } } } ],
  { fullDocument: "updateLookup" })
db.products.updateOne({ _id: 1 }, { $set: { price: 22 } })
const ev = cs.next()
ev.operationType                     // → update
ev.updateDescription.updatedFields   // → { price: 22 }
ev.fullDocument.name                 // → Desk lamp
const token = ev._id                 // save it to resume later
cs.close()

What to learn

  • Open a change stream on a collection, a database or a deployment
  • Filter events with a $match pipeline; event fields and operation types
  • fullDocument: "updateLookup" and pre-/post-images
  • Resume tokens, resumeAfter / startAfter, and the oplog window
  • Patterns: cache invalidation, live updates, outbox to Kafka

Free resources

Practice

Write a worker that watches orders and prints a line for every new paid order. Store the resume token after each event; kill the worker, insert three orders, restart it and check it prints exactly those three. Then push the events to a browser with server-sent events or WebSockets.

Geospatial queries and text indexes

Store locations as GeoJSON points ([longitude, latitude], in that order) with a 2dsphere index, and you can ask "what's near me?" with $near, "what's inside this area?" with $geoWithin, or get distances with $geoNear. A text index gives simple keyword search with stemming and stop words via $text; for relevance tuning, autocomplete and typo tolerance, use MongoDB Search (next topics).

use city
db.cafes.drop()
db.cafes.insertMany([
  { name: "Bean There", loc: { type: "Point",
      coordinates: [73.8567, 18.5204] } },
  { name: "Filter Kaapi", loc: { type: "Point",
      coordinates: [73.8077, 18.5590] } } ])
db.cafes.createIndex({ loc: "2dsphere" })
db.cafes.find({ loc: { $near: { $geometry: { type: "Point",
    coordinates: [73.855, 18.52] }, $maxDistance: 2000 } } },
  { _id: 0, name: 1 })               // within 2 km
// → [ { name: 'Bean There' } ]
db.cafes.createIndex({ name: "text" })
db.cafes.find({ $text: { $search: "kaapi" } }, { _id: 0, name: 1 })
// → [ { name: 'Filter Kaapi' } ]

What to learn

  • GeoJSON points, lines and polygons; longitude comes first
  • 2dsphere indexes, $near, $geoWithin, $geoIntersects
  • $geoNear in aggregation for distances and sorting
  • Text indexes, $text, text score and language options
  • The limits of text indexes compared with MongoDB Search

Free resources

Practice

Load 200 points of interest in your city. Find the 5 nearest to a point with their distances, all points inside a polygon you draw on geojson.io, and the nearest open one using an extra filter. Add a text index on descriptions and search them.

Time series collections

Time series collections store measurements over time (sensor readings, prices, metrics) in compressed buckets automatically, so you write one document per reading and still get the storage and speed of the bucket pattern. You set a timeField, an optional metaField (the sensor or ticker), a granularity and optional automatic expiry. In MongoDB 9.0 they're stored as a single collection of buckets and can be renamed.

use iot
db.readings.drop()
db.createCollection("readings", { timeseries: {
  timeField: "ts", metaField: "sensor", granularity: "minutes" },
  expireAfterSeconds: 60 * 60 * 24 * 30 })      // keep 30 days
db.readings.insertMany([
  { sensor: { id: "s1", room: "lab" }, ts: new Date(), temp: 21.5 },
  { sensor: { id: "s1", room: "lab" }, ts: new Date(), temp: 22.1 },
  { sensor: { id: "s2", room: "hall" }, ts: new Date(), temp: 19 } ])
db.readings.aggregate([
  { $group: { _id: "$sensor.id", avg: { $avg: "$temp" } } },
  { $sort: { _id: 1 } } ])
// → [ { _id: 's1', avg: 21.8 }, { _id: 's2', avg: 19 } ]

What to learn

  • When to use a time series collection instead of a normal one or the bucket pattern
  • timeField, metaField, granularity and bucket settings
  • Automatic expiry with expireAfterSeconds
  • Downsampling with $setWindowFields and $merge
  • Limits on updates and deletes, and secondary indexes on time series

Free resources

Practice

Simulate 10 sensors writing one reading every second for an hour. Store them in a time series collection and in a normal one, compare the storage size with db.collection.stats(), and build a pipeline that gives per-sensor 5-minute averages.

GridFS and storing files

GridFS splits files larger than the 16 MB document limit into chunks across two collections (fs.files and fs.chunks) and lets drivers stream them back. It's handy when files must live with your data and share its backups and replication. For most web apps, though, an object store (S3 or similar) plus a document holding the file's URL and metadata is cheaper and simpler.

What to learn

  • How GridFS stores files: files and chunks, chunk size
  • Upload, download and delete with your driver's GridFS bucket
  • mongofiles from the command line
  • GridFS versus an object store with a metadata document
  • Small binary data (thumbnails) in a BinData field instead

Free resources

Practice

Upload a 50 MB video with mongofiles, look at fs.files and count the chunks, then stream it back from code and compare the checksum with the original using the hash generator.

Am I ready? Stage 3 quiz

You run a transaction on a standalone mongod and get an error. Why?

  1. Transactions need Atlas
  2. Transactions only work on time series collections
  3. You must create an index first
  4. Transactions need a replica set or sharded cluster

Transactions rely on replication machinery. A single-member replica set is enough for development.

A payment write must not be lost if the primary crashes right after acknowledging it. Which write concern?

  1. w: "majority"
  2. w: 0
  3. w: 1 with no journaling
  4. Read preference secondary

A majority-acknowledged write survives a failover; a w: 1 write can be rolled back if the primary dies before replicating it.

Your cache-invalidation worker crashes for five minutes. How does it avoid missing changes when it restarts?

  1. It re-reads every document
  2. It polls with find() every second instead
  3. It resumes the change stream from the last saved resume token
  4. Change streams replay everything from the beginning automatically

Resume tokens let a change stream continue after the last processed event, as long as the oplog still holds that point.

You store a location as coordinates: [18.52, 73.85] (latitude first) and the results look wrong. What's the problem?

  1. You need a text index
  2. GeoJSON expects longitude first: [73.85, 18.52]
  3. Coordinates must be strings
  4. 2dsphere only works in Atlas

GeoJSON order is [longitude, latitude]. Swapping them puts your points somewhere else entirely.

Users search "office chiar" and expect "Office chair". What's the best MongoDB tool?

  1. A case-insensitive $regex
  2. A unique index on name
  3. A text index with $text
  4. MongoDB Search with $search and fuzzy matching

Regex and text indexes don't tolerate typos. $search with fuzzy matches within an edit distance and ranks by relevance.

Stage 4 · Advanced MongoDB in production

Running MongoDB well means surviving failures, growing past one server, keeping intruders out, being able to restore last Tuesday's data and noticing problems before users do. You can practise all of it on your laptop with Docker Compose.

Replica sets and high availability

A replica set is a group of mongod processes holding the same data: one primary takes writes and records them in the oplog, and secondaries copy that log. If the primary fails, the members hold an election and a secondary takes over, usually within about 10 to 12 seconds; drivers find the new primary on their own. Use at least three data-bearing members, spread over failure zones.

# three members on one Docker network (names resolve inside it)
docker network create mongonet
for n in 1 2 3; do
  docker run -d --name m$n --network mongonet mongo:9.0 --replSet rs0
done
docker exec m1 mongosh --quiet --eval 'rs.initiate({ _id: "rs0",
  members: [ { _id: 0, host: "m1:27017" },
             { _id: 1, host: "m2:27017" },
             { _id: 2, host: "m3:27017" } ] })'
# after a few seconds: who is primary?
docker exec m1 mongosh --quiet --eval 'rs.status().members.map(
  m => m.name + " " + m.stateStr).join("\n")'
# one PRIMARY and two SECONDARY lines, for example:
# m1:27017 SECONDARY
# m2:27017 PRIMARY
# m3:27017 SECONDARY
docker stop m2     # stop the primary: another member takes over

What to learn

  • Primary, secondaries, the oplog and how replication works
  • Elections, priority, votes, and why you need an odd number of voting members
  • Arbiters, hidden and delayed members, and why arbiters are discouraged
  • rs.status(), rs.conf(), rs.stepDown(), replication lag and the oplog window
  • Rollbacks, and how majority write concern prevents them

Free resources

Practice

Write the replica set above as a Compose file. Run your products API against it with a load test, stop the primary in the middle, and measure how long writes fail. Then check with rs.printSecondaryReplicationInfo() how far behind each secondary is.

Sharding

Sharding spreads one collection over several replica sets (shards). Apps connect to mongos routers, which use metadata on the config servers to send each query to the right shards; the balancer moves ranges of data between shards to keep them even. The shard key is the big decision: it should have high cardinality, spread writes evenly and appear in most queries, or queries become slow scatter-gather operations. You can change it later with reshardCollection, but it's costly.

// run in mongosh connected to a mongos router
sh.enableSharding("shop")
sh.shardCollection("shop.orders", { customerId: "hashed" })
sh.status()                         // shards, databases, chunks
db.getSiblingDB("shop").orders.getShardDistribution()
// targeted: includes the shard key, so it goes to one shard
db.getSiblingDB("shop").orders.find({ customerId: 42 })
// scatter-gather: no shard key, so every shard is asked
db.getSiblingDB("shop").orders.find({ status: "new" })

What to learn

  • When you need sharding, and why a bigger server or better indexes come first
  • Components: shards, mongos, config servers, the balancer
  • Choosing a shard key: cardinality, frequency, monotonic keys; hashed versus ranged
  • Targeted versus scatter-gather queries; zones for data locality
  • Resharding, and moving unsharded collections between shards

Free resources

Practice

Build a small sharded cluster with Compose: a config server replica set, two one-member shards and a mongos. Shard an orders collection twice, once on { createdAt: 1 } and once on { customerId: "hashed" }, insert 200,000 orders each time and compare getShardDistribution(). Use explain to tell targeted queries from scatter-gather ones.

Security: authentication, roles, TLS and encryption

Thousands of MongoDB servers have been wiped and ransomed because they were open to the internet with no password. The basics stop that: turn on authentication (the Docker image does it when you set MONGO_INITDB_ROOT_USERNAME / _PASSWORD), give each app a user with only the roles it needs, bind to private networks, use TLS, and encrypt data at rest. For the most sensitive fields, Client-Side Field Level Encryption and Queryable Encryption encrypt in the driver, so the server never sees plain text.

use admin
db.createUser({ user: "shopApp", pwd: passwordPrompt(),
  roles: [ { role: "readWrite", db: "shop" } ] })
db.createRole({ role: "reportReader", privileges: [
  { resource: { db: "shop", collection: "orders" },
    actions: ["find"] } ], roles: [] })
db.createUser({ user: "analyst", pwd: passwordPrompt(),
  roles: ["reportReader"] })
db.getUser("shopApp").roles
// → [ { role: 'readWrite', db: 'shop' } ]
// app: mongodb://shopApp:<password>@db.internal:27017/shop
//        ?authSource=admin&tls=true

What to learn

  • Enable access control; SCRAM users, x.509 and, in Enterprise or Atlas, LDAP and OIDC
  • Built-in roles (read, readWrite, dbAdmin, clusterMonitor…) and custom roles
  • Network exposure: bindIp, firewalls, Atlas IP access lists and private endpoints
  • TLS for clients and between members; keyfiles or x.509 for internal auth
  • Encryption at rest, CSFLE and Queryable Encryption; auditing

Free resources

Practice

Start MongoDB with a root user, create an app user with readWrite on one database and a read-only analyst user. Check the analyst can't write or read other databases. Generate a self-signed certificate, require TLS, and confirm a plain connection is refused. Write the security checklist for your deployment.

Backups, restores and upgrades

A backup you haven't restored is a hope, not a backup. mongodump is fine for small databases; larger deployments use filesystem or cloud snapshots (with journaling on the same volume) or a managed backup with point-in-time recovery from the oplog, as Atlas provides. Plan upgrades too: MongoDB supports upgrading one major version at a time (for example 7.0 → 8.0 → 9.0), replica set members one by one, then raising the feature compatibility version.

# consistent dump of a replica set, including oplog entries
# written during the dump
mongodump --uri "mongodb://localhost:27017/?replicaSet=rs0" \
  --oplog --gzip --archive=full-$(date +%F).gz

# restore into a test instance and replay the oplog slice
mongorestore --uri "mongodb://localhost:27018" --oplogReplay \
  --gzip --archive=full-2026-11-05.gz

# check the feature compatibility version before and after an upgrade
mongosh --quiet --eval 'db.adminCommand({ getParameter: 1,
  featureCompatibilityVersion: 1 })'

What to learn

  • Backup methods: mongodump, filesystem snapshots, managed backups
  • Point-in-time recovery and the oplog
  • Regular restore tests, and recovery time and recovery point targets
  • Rolling upgrades of a replica set and setting featureCompatibilityVersion
  • Release types: yearly major versions with five years of support, and minor releases

Free resources

Practice

Script a nightly mongodump --oplog of your replica set with seven days of retention. Then run a fire drill: drop a collection "by accident", restore last night's dump into a separate instance, copy the collection back, and time the whole recovery. Upgrade a test replica set from 8.0 to 9.0 one member at a time.

Monitoring and diagnostics

Watch a few signals: operation latency, connections, replication lag, the WiredTiger cache (how much of your working set fits in RAM), disk, and slow queries. db.serverStatus() holds most raw numbers, db.currentOp() shows what's running now, the server log records every operation slower than 100 ms, and the database profiler can save them to a collection. Atlas has charts and alerts built in; self-managed setups typically use Prometheus with an exporter and Grafana, or MongoDB's own Ops Manager.

const s = db.serverStatus()
s.connections.current                       // open connections
s.opcounters                                // inserts, queries, …
s.wiredTiger.cache["bytes currently in the cache"]
// operations running for more than 5 seconds
db.currentOp({ active: true, secs_running: { $gt: 5 } })
// log and profile operations slower than 50 ms in this database
use shop
db.setProfilingLevel(1, { slowms: 50 })
db.system.profile.find().sort({ ts: -1 }).limit(5)
db.setProfilingLevel(0)

What to learn

  • Key metrics: latency, opcounters, connections, replication lag, cache usage, disk
  • serverStatus, currentOp, killOp, db.stats() and collection stats
  • Slow query log, slowms and the database profiler
  • $queryStats for query shapes (on by default for a sample in 9.0)
  • Atlas metrics and alerts, or Prometheus + Grafana for self-managed

Free resources

Practice

Run a load test with one deliberately unindexed query. Find it three ways: in the slow query log, in the profiler and with currentOp. Add the index and show the improvement. Then set up a Grafana dashboard (or Atlas alerts) for connections, replication lag and slow operations.

Performance tuning

Most MongoDB performance problems come from the same few places: missing or wrong indexes, a working set bigger than RAM, documents and arrays that grew too large, too many connections, and slow aggregation stages. Fix them in that order before buying hardware. Know the server's guard rails too: MongoDB 9.0 limits a single operation to 1 GB or 20% of RAM by default, and maxTimeMS stops runaway queries.

What to learn

  • A tuning routine: find slow queries, explain them, fix indexes or the model, measure again
  • Working set, the WiredTiger cache and when you need more RAM
  • Connection pool sizing across many app instances
  • maxTimeMS, query settings and per-operation memory limits
  • Production notes: file system, swap, transparent huge pages, ulimits

Free resources

Practice

Take your order API, load-test the three busiest endpoints and record p95 latency. Find the worst query, fix it (index, projection, model change or maxTimeMS), and load-test again. Write a one-page before-and-after report.

Atlas and running MongoDB on Kubernetes

MongoDB Atlas runs MongoDB for you on AWS, Google Cloud or Azure: backups, scaling, upgrades, monitoring, search and vector search are built in, and the free M0 tier is enough for learning. The Atlas CLI and Terraform provider manage it as code. If you must self-host on Kubernetes, use an operator (MongoDB's Kubernetes Operator or a community one) rather than hand-written StatefulSets.

What to learn

  • Atlas tiers: free M0, Flex and dedicated clusters; projects and organisations
  • Network access: IP access lists, VPC peering and private endpoints
  • Atlas CLI and the Terraform provider for repeatable setups
  • Managed backups, auto-scaling and the Performance Advisor
  • Operators for MongoDB on Kubernetes, and what they automate

Free resources

Practice

Create an Atlas project and a free cluster with the Atlas CLI or Terraform, including a database user and an IP access list entry, all from code. Point your API at it, load sample data and look at the Performance Advisor's suggestions. Destroy it all with one command.

Capstone project and certification

Bring it all together in one project you can show in an interview, and decide whether a certificate is worth it for you. MongoDB University's free courses cover the developer and DBA exam topics, and the exams themselves are optional.

What to learn

  • Design a schema from a workload, and defend embed-versus-reference choices
  • Index every important query and prove it with explain
  • Use aggregation, a transaction and a change stream where they genuinely fit
  • Run it on a secured three-member replica set with backups and monitoring
  • Review the exam topics if you plan to certify

Free resources

Practice

Build "EventHub", a ticketing app: events with a validated schema, search with autocomplete, nearby events by location, ticket purchases in a transaction that never oversells, a change stream that emails buyers, a daily sales $merge report, and "similar events" with vector search. Run it on a secured replica set with nightly backups, load-test it, stop the primary during the test, and write up what happened.

Am I ready? Stage 4 quiz

Why should a replica set have three data-bearing members rather than two?

  1. With two, losing one leaves no majority, so no primary can be elected
  2. Two members can't replicate
  3. Drivers need exactly three hosts
  4. Three members make reads three times faster

Elections need a majority of voting members. With two, one failure leaves one of two votes, which isn't a majority, so the set becomes read-only.

You shard orders on { createdAt: 1 }. What goes wrong?

  1. Nothing: time is a perfect shard key
  2. Queries by date become scatter-gather
  3. Every new order goes to the shard holding the newest range, creating a write hotspot
  4. You can't index other fields

A key that always increases sends all inserts to one shard. Hashing it, or using a compound key that spreads writes, avoids the hotspot.

What's the single most important step to stop your MongoDB being wiped by attackers?

  1. Use a non-default port
  2. Rename the admin database
  3. Turn off journaling
  4. Enable authentication and never expose the server to the public internet

Most ransom attacks hit servers with no password reachable from anywhere. Ports and names are no protection.

How do you know your backups actually work?

  1. The backup job exits with code 0
  2. You restore them regularly into a test environment and check the data
  3. The files are larger than zero bytes
  4. Atlas or the cloud provider says so

Only a restore proves a backup. Test restores also tell you how long recovery really takes.

Queries got slow as data grew, and serverStatus shows the WiredTiger cache constantly full and lots of disk reads. What's the likely cause?

  1. Too many replica set members
  2. The oplog is too big
  3. The working set (hot data plus indexes) no longer fits in RAM
  4. The shell's batch size is too small

When hot data and indexes don't fit in cache, reads go to disk. Remove unused indexes, shrink documents or add RAM, or shard.

How to use this roadmap

  • Type the examples yourself. Start MongoDB with the commands in Install MongoDB and run each example in mongosh, a terminal or Python. In shell examples, // → shows the reply you should see (shortened with … where it's long); in terminal examples, everything after # is an explanation. The examples in stage 1 and 2 build on each other, so run them in order. Every mongosh example was run against MongoDB 9.0.4 before publishing.
  • Use the filter. Developer is for people building apps: CRUD, modeling, indexes, drivers, transactions and change streams. DBA & operations is for people running MongoDB: tools, replica sets, sharding, security, backups and monitoring. Aggregation, search & AI focuses on pipelines, time series, full-text and vector search. The labels are a guide, not an official exam outline.
  • Certification is optional. MongoDB offers proctored associate certifications for developers and database administrators through MongoDB University, which also has free courses for every topic. Prices and exam formats change, so check the certification page for current details. Stages 1 to 3 cover the developer exam's ground; add stage 4 for the DBA exam.
  • It's free to follow. MongoDB Community Server, mongosh, Compass, the database tools, the drivers and an Atlas M0 cluster are all free, and every resource linked here is free. You only pay for bigger managed clusters or Enterprise features.
  • Watch for outdated guides. Tutorials that use the mongo shell (removed in 6.0), db.collection.insert(), update() or count() (replaced by insertOne/insertMany, updateOne/updateMany and countDocuments), or that say "MongoDB has no transactions" or "no joins" are years out of date.
  • Track your progress. Ticking the first item in a topic marks it in progress; ticking them all marks it done. Progress stays in this browser. Use Export to move it to another device, or Share progress to send a link. Optional topics (dashed borders) don't count towards the percentage.
  • Related roadmaps: compare with relational databases in SQL & Databases, cache in front of MongoDB with Redis, build the API around it with Backend, see how it fits large systems in System Design, stream its changes with Apache Kafka, build RAG apps with AI Engineering, and run it with DevOps, Kubernetes and AWS.

SQL to MongoDB cheat sheet

Database / table / rowdatabase / collection / document · topic
INSERTinsertOne(), insertMany() · topic
SELECT … WHERE … ORDER BY … LIMITfind(filter, projection).sort().limit() · topic
UPDATE / DELETEupdateOne() with $set, $inc…; deleteMany() · topic
Child table with a foreign keyan embedded array, or a referenced collection · topic
CHECK constraints / column types$jsonSchema validator · topic
CREATE INDEXcreateIndex(); compound indexes follow ESR · topic
EXPLAIN ANALYZEexplain("executionStats") · topic
GROUP BY / HAVING$group then $match · topic
JOIN / window functions$lookup / $setWindowFields · topic
BEGIN … COMMITa session with withTransaction() · topic
Triggers / logical replicationchange streams · topic
Full-text search / pgvector$search / $vectorSearch · topic
Primary and replicasreplica set · topic
Partitioning across serverssharding · topic
pg_dump / psqlmongodump / mongosh · topic

Check and shape documents with the JSON formatter and JSON diff, convert CSV for mongoimport with JSON ⇄ CSV, generate test data with the fake data generator and read ObjectId times with the timestamp converter; all of them run in your browser and send nothing anywhere. Product and service names are examples, not endorsements. MongoDB is a registered trademark of MongoDB, Inc.; DevToolbox is not affiliated with MongoDB, Inc. Facts and links on this page were checked on 5 November 2026.