The Complete MongoDB Guide

By

Published · Updated

Tagged: Database

Learn MongoDB 8 from scratch: BSON, CRUD in mongosh, Node.js driver, schema design, $jsonSchema validation, ESR indexes, aggregations, transactions, and backups.

If you want to learn MongoDB from scratch without drowning in enterprise buzzwords or guessing how to structure your collections, this guide is for you.

MongoDB is the most widely used document database in the world. Instead of splitting one entity across five joined SQL tables, it stores rich, JSON-like documents inside collections with flexible schemas, fast indexes, and a powerful aggregation pipeline.

I have used both PostgreSQL and MongoDB across real production projects over the years. When people run into trouble with MongoDB, it is almost never the database engine itself. It is usually because they tried to model MongoDB like a relational SQL database, skipped compound indexes, or let arrays grow without a cap.

In this guide, we start from zero and build all the way to a production Node.js API.

We learn what a document database is, install MongoDB and connect with mongosh, understand BSON types and _id, master CRUD queries and array operators, connect cleanly from Node.js, design schemas (embedding vs referencing), enforce rules with $jsonSchema, speed up queries with ESR indexes and explain(), build aggregation pipelines, watch live Change Streams, use ACID transactions properly, and cover backups and security.

Every schema validation check, 50,000-document explain("executionStats") benchmark, and aggregation pipeline in this guide was verified live on my Mac:

SoftwareVersion
MongoDB Server8.3.17
Official Node.js mongodb driver7.9.1
Node.js22.23.5

What is MongoDB (and how it differs from SQL)?

In a relational database like PostgreSQL, MySQL, or SQLite, we store data in rigid tables made of rows and columns, and we connect related tables using foreign keys and JOIN queries.

MongoDB is a document database. We store data in collections made of documents, and each document looks just like a JavaScript object:

{
  "_id": "6749a3f1c8e2b4a109f01234",
  "title": "MongoDB Handbook",
  "author": {
    "name": "Flavio Copes",
    "city": "Milan"
  },
  "tags": ["database", "mongodb", "nodejs"],
  "pages": 44
}

Look closely at that document. author is an embedded object and tags is an array sitting right inside the book. Reading this book takes one single database lookup with zero joins.

Database(bookstore)Collection(books)Collection(orders)Document 1{_id, title, tags:[...]}Document 2{_id, title, tags:[...]}

SQL vs MongoDB terminology

If you already know SQL, this quick mapping translates every concept immediately:

SQL (PostgreSQL / MySQL)MongoDB
DatabaseDatabase
TableCollection
RowDocument
ColumnField
Primary key (id)_id (ObjectId by default)
JOINEmbedded subdocument or $lookup
GROUP BYAggregation pipeline ($group)
WHEREFilter object (find({ ... }))

When should you pick MongoDB vs PostgreSQL?

I always tell beginners to pick the database that matches how their data actually behaves.

MongoDB is a great fit when your data is naturally hierarchical (product catalogs with varying attributes, CMS pages, user profiles with nested settings, order snapshots, event logs) or when your data shape evolves rapidly while you ship.

If your core domain is heavy multi-table accounting with dozens of strict relational joins and foreign-key constraints across normalized tables, PostgreSQL is usually a better default.

Installing MongoDB and connecting with mongosh

You have three fast ways to run MongoDB while learning.

Option 1: Docker or OrbStack (my favorite for local dev)

Spinning up an official MongoDB 8 container takes one command and keeps your laptop spotless:

docker run -d --name mongo-local -p 27017:27017 mongo:8

When you are finished experimenting, stop and remove it with docker rm -f mongo-local.

Option 2: Homebrew on macOS

If you prefer running MongoDB as a native macOS background service:

brew tap mongodb/brew
brew install mongodb-community mongosh
brew services start mongodb-community

Option 3: MongoDB Atlas (hosted free tier)

If you want zero local installation, MongoDB Atlas gives you a free cloud replica set and a mongodb+srv://... connection string you can drop straight into Node.js or mongosh.

Exploring with mongosh

MongoDB’s modern interactive shell is mongosh (it replaced the legacy mongo binary years ago). Connect to your local server:

mongosh

Inside mongosh, switch to a new database called bookstore. Notice MongoDB does not create a database or collection on disk until you insert the first document:

use bookstore

db.books.insertOne({
  title: 'MongoDB Handbook',
  pages: 44,
  tags: ['mongodb', 'nodejs'],
  publishedAt: new Date(),
})

db.books.find()

Keep four everyday mongosh commands handy:

  • show dbs lists all non-empty databases.
  • db prints the currently selected database name.
  • show collections lists collections inside the current database.
  • db.books.countDocuments() counts documents in books.

Documents, BSON types, and _id

When we write documents in mongosh or JavaScript, they look like JSON. Under the hood on disk and over the network, MongoDB stores BSON (Binary JSON).

JSON only has six basic types (string, number, boolean, null, object, array), which is too limited for a real database. BSON extends JSON with exact binary types that production apps depend on:

BSON TypeJavaScript / mongosh syntaxWhy it matters
ObjectIdnew ObjectId()12-byte unique ID with embedded creation timestamp
Datenew Date()Real UTC millisecond timestamp, sortable and indexable
Int32 / Int64Int32(42) / Long(9000000000)Exact integer storage
Double3.14Standard IEEE 754 floating-point number
Decimal128Decimal128.fromString('19.99')Exact base-10 decimals for money (no 0.1 + 0.2 drift)
BinDataBinary.createFromBase64(...)Raw byte buffers, hashes, or binary UUIDs
Boolean / Nulltrue, false, nullStandard flags and explicit empty values

For prices and balances, I usually store integer cents (priceCents: 1999) or Decimal128, never raw floating-point dollars.

How _id and ObjectId work

Every single document in a MongoDB collection must have a unique _id field.

If we omit _id when inserting, the driver automatically generates a 12-byte ObjectId. MongoDB also creates a unique index on _id for every collection automatically, so looking up a document by _id is always instant.

One neat trick: the first 4 bytes of an ObjectId store the Unix timestamp in seconds when it was generated! In Node.js or mongosh, you can inspect it anytime:

const id = new ObjectId()
console.log(id.getTimestamp()) // 2026-12-03T09:15:00.000Z

That also means sorting by { _id: -1 } roughly sorts newest-first for free!

You can supply your own custom _id (like a slug 'mongodb-handbook' or an external Stripe ID) whenever it is guaranteed unique and immutable. Once a document is inserted, its _id can never be changed.

Finally, keep one hard ceiling in mind: a single BSON document has a maximum size of 16 MB. That sounds huge, and for normal records it is, unless you accidentally append unlimited logs or comments into one array!

Creating and reading documents

Let’s practice the bread-and-butter CRUD operations we run every day.

Inserting documents

Use insertOne() for a single document and insertMany() for inserting a batch of documents in one round-trip:

await db.collection('books').insertMany([
  { title: 'JavaScript Handbook', category: 'programming', pages: 39, priceCents: 0 },
  { title: 'TypeScript Handbook', category: 'programming', pages: 43, priceCents: 0 },
  { title: 'Linux Server Handbook', category: 'infrastructure', pages: 114, priceCents: 0 },
  { title: 'HTML Forms Handbook', category: 'programming', pages: 47, priceCents: 0 },
])

By default, insertMany() stops at the first error (like a duplicate unique email). Pass { ordered: false } when importing bulk records if you want MongoDB to skip bad rows and still insert all valid ones in parallel.

Reading, projecting, and sorting

find(filter, options) returns a cursor, while findOne(filter, options) returns the first matching document or null:

// Find all programming books, returning only title and pages (hide _id)
const books = await db
  .collection('books')
  .find(
    { category: 'programming' },
    { projection: { title: 1, pages: 1, _id: 0 } },
  )
  .sort({ pages: -1 })
  .limit(10)
  .toArray()

Look at two projection rules:

  • Pass 1 to include a field, or 0 to exclude a field.
  • You cannot mix 1 and 0 in the same projection object, with one exception: you can include specific fields and still set _id: 0 to hide _id.

Always project only the fields your screen or API response actually needs. Skipping a large 50 KB bodyMarkdown field when rendering a list of blog titles cuts network traffic and memory usage dramatically.

Counting documents

Use countDocuments(filter) for accurate filtered counts, and estimatedDocumentCount() when you just want a fast approximate total size of the whole collection (it reads collection metadata in O(1) time without scanning documents).

Keyset pagination vs .skip()

Beginners naturally paginate pages like this:

// Slow once page gets large!
const page500 = await books.find().sort({ _id: 1 }).skip(10000).limit(20).toArray()

Why does .skip(10000) get slow? Because MongoDB still has to walk through and throw away all 10,000 skipped entries before returning your 20 rows!

For large feeds or APIs, use keyset (cursor) pagination. Remember the _id of the last item returned on page 1, and ask for the next 20 items after it:

const filter = lastSeenId ? { _id: { $gt: new ObjectId(lastSeenId) } } : {}
const nextPage = await books.find(filter).sort({ _id: 1 }).limit(20).toArray()

Because _id is indexed, jumping straight to page 500 is just as fast as loading page 1!

Query operators, dot notation, and querying arrays

MongoDB uses $-prefixed operators inside filter objects to express ranges, sets, missing fields, and complex array matches.

OperatorMeaningExample
$eq / $neEqual / not equal{ status: { $ne: 'cancelled' } }
$gt / $gteGreater than / or equal{ pages: { $gte: 40 } }
$lt / $lteLess than / or equal{ priceCents: { $lt: 5000 } }
$in / $ninMatches any value in array / none{ status: { $in: ['paid', 'shipped'] } }
$or / $andLogical OR / AND{ $or: [{ category: 'ai' }, { pages: { $gt: 80 } }] }
$notNegates an operator expression{ pages: { $not: { $lt: 20 } } }
$existsField is present (true) or absent (false){ deletedAt: { $exists: false } }
$typeMatches a specific BSON type{ priceCents: { $type: 'int' } }
$allArray contains every listed value{ tags: { $all: ['mongodb', 'nodejs'] } }
$sizeArray has exact length{ tags: { $size: 3 } }
$elemMatchOne single array element matches all rules{ items: { $elemMatch: { sku: 'TS', qty: { $gte: 2 } } } }

Querying nested objects with dot notation

To match a field inside an embedded object, put quotes around the dotted path:

await db.collection('books').find({ 'author.city': 'Milan' }).toArray()

The $elemMatch array pitfall

Let’s look at a bug that bites almost everyone when querying an array of objects, like order line items:

// Document in orders collection:
{
  items: [
    { sku: 'TS', qty: 1 },
    { sku: 'JS', qty: 5 }
  ]
}

Suppose I want orders that bought at least 2 copies of 'TS'. If I write this:

// BUG: matches the document above!
orders.find({ 'items.sku': 'TS', 'items.qty': { $gte: 2 } })

Why did that match?! Because MongoDB checks each condition independently across the whole array: item 0 has sku: 'TS' AND item 1 has qty: 5!

To require that the same single array element satisfies both conditions, wrap them in $elemMatch:

// CORRECT: one item must have sku 'TS' AND qty >= 2
orders.find({
  items: { $elemMatch: { sku: 'TS', qty: { $gte: 2 } } },
})

Matching text and regular expressions

When using $regex for prefix search, always anchor it with ^ ({ title: { $regex: '^Mongo' } }) so MongoDB can use a regular B-tree index! An unanchored case-insensitive regex like /mongo/i forces a full collection scan unless you use a dedicated text index or Atlas Search.

Updating, replacing, upserting, and deleting documents

Let’s be super clear about the difference between updating specific fields and replacing an entire document.

Field updates ($set, $unset, $inc, $min, $max)

Always pass update operators to updateOne() or updateMany():

await db.collection('books').updateOne(
  { title: 'MongoDB Handbook' },
  {
    $set: { pages: 44, updatedAt: new Date() },
    $unset: { legacyField: '' },
    $inc: { downloads: 1 },
  },
)

Using $inc: { downloads: 1 } is atomic on the server. If two users download the book at the same millisecond, both increments are counted cleanly with zero lost updates (unlike reading downloads, adding 1 in JavaScript, and writing it back!).

Updating arrays cleanly

MongoDB gives us atomic operators for editing arrays right inside a document:

  • $push appends an element ({ $push: { tags: 'indexes' } }). Combine with $each, $sort, and $slice to keep a capped list of the 10 most recent items!
  • $addToSet appends an item only if it is not already in the array (perfect for unique tags!).
  • $pull removes every array element matching a condition ({ $pull: { tags: 'draft' } }).
  • arrayFilters updates a specific nested object inside an array:
await db.collection('orders').updateOne(
  { _id: orderId },
  { $set: { 'items.$[item].qty': 3 } },
  { arrayFilters: [{ 'item.sku': 'TS' }] },
)

Atomic read-and-update with findOneAndUpdate

Often in a REST API, we want to update a document and immediately return the updated version to the caller in one database round-trip. Use findOneAndUpdate() with { returnDocument: 'after' }:

const updated = await db.collection('books').findOneAndUpdate(
  { _id: new ObjectId(id) },
  { $set: { title: 'Updated Title', updatedAt: new Date() } },
  { returnDocument: 'after' },
)

Without { returnDocument: 'after' }, MongoDB returns the old document from before the update by default!

Upserts (upsert: true + $setOnInsert)

When you want “update if found, otherwise insert”, pass { upsert: true }. Use $setOnInsert for fields like createdAt that should only be set when a brand-new document is created:

await db.collection('dailyStats').updateOne(
  { day: '2026-12-03' },
  {
    $inc: { visits: 1 },
    $setOnInsert: { createdAt: new Date() },
  },
  { upsert: true },
)

Deleting documents safely

Use deleteOne(filter) or deleteMany(filter). Never pass an unchecked user object directly into deleteMany(), and check result.deletedCount to know whether a matching document actually existed.

Bulk writes and streaming cursors

If you need to apply 500 updates or imports in a script, do not loop 500 times calling await collection.updateOne(...) one by one. Each await pays a full network round-trip!

Batch them into one call with bulkWrite():

const result = await db.collection('books').bulkWrite(
  [
    { insertOne: { document: { title: 'New Book', pages: 35 } } },
    {
      updateOne: {
        filter: { title: 'MongoDB Handbook' },
        update: { $inc: { downloads: 10 } },
      },
    },
    { deleteOne: { filter: { title: 'Deprecated Draft' } } },
  ],
  { ordered: false },
)

console.log({
  inserted: result.insertedCount,
  modified: result.modifiedCount,
  deleted: result.deletedCount,
})

And when exporting or processing 100,000 documents from Node.js, never call .toArray() (which tries to load all 100,000 documents into RAM at once). Stream the cursor with for await:

const cursor = db.collection('orders').find({ status: 'paid' }).batchSize(500)

for await (const order of cursor) {
  // Process one document at a time with constant memory
}

Using MongoDB from Node.js

Install the official Node.js driver:

npm init -y
npm pkg set type=module
npm install mongodb

One shared MongoClient per application

Here is the most important performance rule for Node.js apps: create one shared MongoClient when your process starts, and reuse it across every single request.

The official driver automatically manages a healthy connection pool behind the scenes. Opening and closing a fresh MongoClient inside every Express route leaks sockets and slows every request down by 50 to 100 ms.

// db.js
import { MongoClient } from 'mongodb'

const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017'

export const client = new MongoClient(uri, {
  maxPoolSize: 20,
  serverSelectionTimeoutMS: 5000,
})

await client.connect()
export const db = client.db(process.env.MONGODB_DB || 'bookstore')

export async function closeDb() {
  await client.close()
}

If you write TypeScript, the official driver gives you first-class generic types with zero extra ORM overhead:

interface Book {
  title: string
  category: 'programming' | 'infrastructure' | 'ai'
  pages: number
  createdAt: Date
}

const books = db.collection<Book>('books')

Official mongodb driver vs Mongoose

People often ask me whether they should use Mongoose or the official mongodb driver.

Years ago, the raw driver felt clunky and Mongoose filled a huge gap. Today, the official mongodb driver has clean async/await APIs, built-in TypeScript generics, and works straight alongside Zod (for request validation) and MongoDB’s native $jsonSchema (for database validation).

I reach for the official mongodb driver + Zod on every new Node.js project. You skip Mongoose’s hidden middleware, hydrated document overhead, and version-mismatch surprises, and every query you write matches MongoDB’s official documentation word for word.

Data modeling: embedding vs referencing

Once you know CRUD syntax, the real craft of MongoDB is data modeling: deciding whether related data belongs embedded inside one document or referenced in a separate collection by _id.

The golden rule I follow is simple: data that your app reads together should usually live together.

YesNo (grows forever)YesNoIs the child listsmalland bounded (under~100 items)?Read together withparenton almost everyrequest?Reference by IDin a separatecollectionEmbed inside parentdocument (1 read,atomic)
PatternReal-world exampleWhy it works
EmbedOrder + its 3 to 10 line items; User + shipping addressesOne fast read, zero joins, atomic single-document writes
ReferenceBlog post + 5,000 comments; User + 50,000 audit eventsKeeps documents small and prevents unbounded array growth
Subset (Hybrid)Product + 3 most recent reviews embedded; full history in reviewsInstant product page load while full history stays queryable
Extended ReferenceOrder stores { customerId, customerName, customerEmail }Copies immutable snapshot fields so order history survives profile edits

Notice that last pattern (Extended Reference)! In an e-commerce order, copying customerEmail and unitPriceCents straight into the order document is not bad duplication. If the product price increases next month, historical receipts must still show the exact price the customer actually paid!

Avoiding the unbounded array anti-pattern

Pushing every page view, chat message, or webhook log into an array inside a parent document feels convenient during week one. Six months later, that document grows to several megabytes, slows down every read and index update, and eventually crashes on the 16 MB BSON limit.

Whenever a child list can grow without a strict upper bound, put it in its own collection with a parent ID field ({ postId: ObjectId(...), createdAt: Date }) and index { postId: 1, createdAt: -1 }.

Schema validation with $jsonSchema

MongoDB is famous for flexible schemas, and beginners sometimes hear “schemaless” and think anything goes.

In production, I always want two layers of validation:

  1. Application layer (Zod): validates incoming HTTP requests and returns clean 422 error messages to users.
  2. Database layer ($jsonSchema): enforces hard invariants directly inside MongoDB so even a buggy migration script or manual mongosh typo can never corrupt a collection.

Attach a $jsonSchema validator when creating a collection:

await db.createCollection('orders', {
  validator: {
    $jsonSchema: {
      bsonType: 'object',
      required: ['customerEmail', 'status', 'totalCents', 'createdAt'],
      additionalProperties: false,
      properties: {
        _id: { bsonType: 'objectId' },
        customerEmail: { bsonType: 'string', minLength: 5, maxLength: 254 },
        status: { enum: ['pending', 'paid', 'refunded'] },
        totalCents: { bsonType: 'int', minimum: 0 },
        createdAt: { bsonType: 'date' },
      },
    },
  },
  validationLevel: 'strict',
  validationAction: 'error',
})

Notice _id: { bsonType: 'objectId' } is listed inside properties when using additionalProperties: false. If you omit _id with additionalProperties: false, every single insert fails because MongoDB adds _id automatically!

To add or tighten validation on a collection that already has data, run collMod with validationLevel: 'moderate' (so existing legacy rows don’t break until touched) or validationAction: 'warn' first while you audit logs:

await db.command({
  collMod: 'orders',
  validator: { $jsonSchema: { /* updated schema */ } },
  validationLevel: 'moderate',
  validationAction: 'error',
})

Indexes, explain(), and the ESR rule

If you only remember one performance chapter from this guide, make it this one.

Without an index, MongoDB executes a collection scan (COLLSCAN): it reads every single document in the collection from disk or memory to test your filter. That feels fine on 500 documents during local development, then freezes your API once the collection hits 500,000 rows in production.

With the right index, MongoDB executes an index scan (IXSCAN) and jumps directly to the matching entries in under a millisecond.

find({ status:'paid', totalCents:{ $gte: 2000 } }).sort({ createdAt:-1 }).limit(100)No index -> COLLSCAN50,000 docs examined(14 ms)Compound index{ status: 1,createdAt: -1,totalCents: 1 }-> IXSCAN: 100 docsexamined (0 ms)

The ESR rule for compound indexes

When a query filters on multiple fields and sorts the results, the order of keys inside your compound index matters enormously. Follow the ESR rule:

  1. E (Equality) filters first: exact matches like status: 'paid'.
  2. S (Sort) fields second: sort keys like createdAt: -1 (eliminates expensive in-memory sorting!).
  3. R (Range) filters last: operators like $gte, $lt, $in, $ne (totalCents: { $gte: 2000 }).

Create the compound index:

await db.collection('orders').createIndex({
  status: 1,
  createdAt: -1,
  totalCents: 1,
})

Remember the index prefix rule: that single index { status: 1, createdAt: -1, totalCents: 1 } automatically accelerates queries filtering on { status } alone, { status, createdAt }, and { status, createdAt, totalCents }. It does not help a query filtering only on { totalCents }!

Verifying performance with explain('executionStats')

I always ask MongoDB directly whether it used my index instead of guessing:

const plan = await db
  .collection('orders')
  .find({ status: 'paid', totalCents: { $gte: 2000 } })
  .sort({ createdAt: -1 })
  .limit(100)
  .explain('executionStats')

console.log({
  stage: plan.queryPlanner.winningPlan.inputStage?.inputStage?.stage,
  docsExamined: plan.executionStats.totalDocsExamined,
  keysExamined: plan.executionStats.totalKeysExamined,
  nReturned: plan.executionStats.nReturned,
  ms: plan.executionStats.executionTimeMillis,
})

Aim for totalDocsExamined to stay close to nReturned. If nReturned is 100 and totalDocsExamined is 50000, you have a missing or misordered index!

Even better, when every projected field already sits inside the index (with _id: 0), MongoDB executes a covered query with totalDocsExamined: 0, never touching the main collection documents at all!

Here is a verified live run on MongoDB 8.3.17 with 50,000 orders showing $jsonSchema blocking a negative amount, COLLSCAN (50,000 docs examined, 14 ms) dropping to IXSCAN (100 docs examined, 0 ms) after adding our ESR index, plus an aggregation summary:

Verified MongoDB 8.3.17 $jsonSchema validation, 50,000-doc COLLSCAN vs IXSCAN explain, and aggregation output

Specialized index types worth knowing

  • Unique index: createIndex({ email: 1 }, { unique: true }) enforces unique emails (rejecting duplicates with error code 11000).
  • TTL (auto-expiring) index: createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 }) automatically deletes expired login tokens, sessions, or temporary cache rows in the background!
  • Partial index: createIndex({ email: 1 }, { unique: true, partialFilterExpression: { deletedAt: { $exists: false } } }) enforces unique emails only on active accounts while allowing soft-deleted accounts to re-register!
  • Multikey index: creating an index on an array field (createIndex({ tags: 1 })) automatically indexes every individual element inside the array.

One quick trade-off: every extra index takes RAM and slightly slows down insert, update, and delete writes. Only create indexes that match your real production queries, and drop unused ones with dropIndex().

Aggregation pipelines from scratch

Whenever you need totals, averages, revenue by month, tag counts, or multi-step analytics, MongoDB’s aggregation pipeline shines.

Think of a pipeline like Unix pipes (cat | grep | sort | uniq). Documents enter stage 1, get filtered or reshaped, and stream into stage 2 until the final result comes out.

orders collection(50,000 docs)$matchstatus: 'paid'$groupby status -> count,avgCents$sortcount: -1Summary result[{ _id: 'paid',count: 45000,avgCents: 3500 }]

Grouping and summarizing ($match, $group, $sort)

const summary = await db
  .collection('orders')
  .aggregate([
    { $match: { status: 'paid' } },
    {
      $group: {
        _id: '$status',
        count: { $sum: 1 },
        revenueCents: { $sum: '$totalCents' },
        avgCents: { $avg: '$totalCents' },
      },
    },
    { $sort: { revenueCents: -1 } },
  ])
  .toArray()

Always place $match (and $sort when possible) at the very front of the pipeline so MongoDB can use your collection indexes before grouping documents in memory.

Flattening arrays with $unwind

Suppose each book has tags: ['mongodb', 'nodejs'] and you want the top 5 most popular tags across your entire catalog. Use $unwind to turn each array element into its own pipeline document, then $group:

const topTags = await db
  .collection('books')
  .aggregate([
    { $unwind: '$tags' },
    { $group: { _id: '$tags', booksCount: { $sum: 1 } } },
    { $sort: { booksCount: -1 } },
    { $limit: 5 },
  ])
  .toArray()

Joining another collection with $lookup

When you referenced a customerId in orders, $lookup performs a left outer join against customers:

const ordersWithCustomer = await db
  .collection('orders')
  .aggregate([
    { $match: { status: 'paid' } },
    { $sort: { createdAt: -1 } },
    { $limit: 20 },
    {
      $lookup: {
        from: 'customers',
        localField: 'customerId',
        foreignField: '_id',
        as: 'customer',
      },
    },
    { $unwind: { path: '$customer', preserveNullAndEmptyArrays: true } },
  ])
  .toArray()

Make sure foreignField (_id here, or any custom join key) is indexed on the target collection, otherwise $lookup runs a slow collection scan for every single row!

Getting paginated rows AND total count in one round-trip ($facet)

$facet lets you run multiple sub-pipelines over the same matched documents in a single query:

const [result] = await db
  .collection('books')
  .aggregate([
    { $match: { category: 'programming' } },
    {
      $facet: {
        items: [{ $sort: { createdAt: -1 } }, { $limit: 20 }],
        meta: [{ $count: 'total' }],
      },
    },
  ])
  .toArray()

That returns { items: [...20 books], meta: [{ total: 142 }] } in one single database call.

Real-world schema patterns: Computed, Bucket, and Outlier

Embedding vs referencing covers 80% of schema design. When an app scales past a few hundred thousand documents, three classic MongoDB patterns solve the remaining 20% cleanly.

1. The Computed Pattern (pre-calculate hot stats on write)

Suppose your product page shows the total review count and average star rating on every single page load. Running $avg across 10,000 reviews on every view wastes CPU.

Instead, store reviewCount and ratingSum right on the product document and update them atomically whenever a new review arrives:

await db.collection('products').updateOne(
  { _id: productId },
  {
    $inc: { reviewCount: 1, ratingSum: newRating },
    $set: { lastReviewedAt: new Date() },
  },
)

Now rendering the product card reads one tiny document and computes ratingSum / reviewCount in microseconds!

2. The Bucket Pattern (group high-frequency events)

If an IoT sensor or analytics tracker fires once a second, storing one document per second creates 86,400 documents per device per day and balloons your indexes.

With the Bucket Pattern, we pack up to 60 readings (one hour) into a single bucket document using upsert: true:

const hourStart = new Date()
hourStart.setMinutes(0, 0, 0)

await db.collection('sensorBuckets').updateOne(
  { sensorId: 'temp-01', bucketHour: hourStart, count: { $lt: 60 } },
  {
    $push: { readings: { ts: new Date(), celsius: 21.4 } },
    $inc: { count: 1, sumCelsius: 21.4 },
    $setOnInsert: { sensorId: 'temp-01', bucketHour: hourStart },
  },
  { upsert: true },
)

You cut document count and index RAM by 60x while keeping per-hour averages right on the bucket!

3. The Outlier Pattern (protect normal reads from one viral record)

Imagine 99.9% of books have fewer than 200 readers saved in an array, while one viral book hits 50,000 readers.

Rather than penalizing every normal book by forcing an extra join, keep up to 200 items embedded, set hasOverflow: true once that cap hits, and spill extra items into a bookReadersOverflow collection. Your read path checks if (book.hasOverflow) only for the tiny 0.1% of viral outliers!

String matching trips up almost every developer moving from PostgreSQL or MySQL to MongoDB.

Fast case-insensitive lookups and unique emails with collations

If you write { email: { $regex: '^flavio@example\\.com$', $options: 'i' } }, MongoDB cannot use a normal case-sensitive index efficiently, AND a normal unique index on { email: 1 } treats Flavio@example.com and flavio@example.com as two different emails!

Fix both with a collation (strength: 2 ignores letter case while preserving accents):

await db.collection('users').createIndex(
  { email: 1 },
  {
    unique: true,
    collation: { locale: 'en', strength: 2 },
  },
)

To make a query use that collation index, pass the matching collation option to findOne():

const user = await db
  .collection('users')
  .findOne(
    { email: 'FLAVIO@example.com' },
    { collation: { locale: 'en', strength: 2 } },
  )

In practice, I also normalize emails with email.trim().toLowerCase() in my Zod schema before writing so queries stay simple everywhere.

Built-in full-text search ($text)

For lightweight blog or catalog search without adding Elasticsearch or Meilisearch, create a compound text index with field weights (note: a collection can have at most one text index):

await db.collection('books').createIndex(
  { title: 'text', summary: 'text', tags: 'text' },
  { weights: { title: 10, tags: 5, summary: 1 } },
)

const matches = await db
  .collection('books')
  .find(
    { $text: { $search: 'mongodb indexes' } },
    { projection: { title: 1, score: { $meta: 'textScore' } } },
  )
  .sort({ score: { $meta: 'textScore' } })
  .limit(10)
  .toArray()

MongoDB stems English words (indexes matches indexing and indexed) and ranks title matches higher than body matches. When you later need typo tolerance, autocomplete-as-you-type, or vector embeddings, MongoDB Atlas Search ($search / $vectorSearch) plugs right into the aggregation pipeline.

Time-Series collections and geospatial queries (2dsphere)

MongoDB includes specialized storage engines and indexes for two workloads developers used to spin up separate databases for: metrics and maps.

Native Time-Series collections

If you store server metrics, stock prices, or IoT readings, create a native Time-Series collection instead of hand-rolling buckets:

await db.createCollection('requestMetrics', {
  timeseries: {
    timeField: 'ts',
    metaField: 'service',
    granularity: 'minutes',
  },
  expireAfterSeconds: 30 * 24 * 60 * 60, // auto-delete after 30 days
})

await db.collection('requestMetrics').insertOne({
  ts: new Date(),
  service: { name: 'checkout-api', region: 'eu-west' },
  latencyMs: 42,
  status: 200,
})

Behind the scenes, MongoDB automatically packs readings into compressed columnar buckets, slashing disk storage and speeding up time-range aggregations while letting you insert normal single documents.

Geospatial queries with GeoJSON and 2dsphere

To find stores, restaurants, or drivers near a user’s coordinates, store locations as standard GeoJSON points and create a 2dsphere index.

Watch one famous gotcha: GeoJSON always puts [longitude, latitude] (X then Y), the opposite of Google Maps’ (lat, lng) order!

await db.collection('places').createIndex({ location: '2dsphere' })

await db.collection('places').insertOne({
  name: 'Duomo Coffee',
  location: {
    type: 'Point',
    coordinates: [9.1919, 45.4642], // [longitude, latitude] in Milan
  },
})

// Find places within 2 km of Milan center, sorted nearest first
const nearby = await db
  .collection('places')
  .find({
    location: {
      $near: {
        $geometry: { type: 'Point', coordinates: [9.19, 45.464] },
        $maxDistance: 2000, // meters
      },
    },
  })
  .limit(10)
  .toArray()

Advanced aggregation recipes

Once you are comfortable with $match, $group, and $lookup, five extra aggregation stages unlock real analytics directly inside MongoDB without pulling megabytes of rows into Node.js.

1. Monthly revenue charts with $dateTrunc

const monthlyRevenue = await db
  .collection('orders')
  .aggregate([
    { $match: { status: 'paid' } },
    {
      $group: {
        _id: { $dateTrunc: { date: '$createdAt', unit: 'month' } },
        orders: { $sum: 1 },
        revenueCents: { $sum: '$totalCents' },
      },
    },
    { $sort: { _id: 1 } },
  ])
  .toArray()

2. Price histograms with $bucket

const priceRanges = await db
  .collection('orders')
  .aggregate([
    {
      $bucket: {
        groupBy: '$totalCents',
        boundaries: [0, 2000, 5000, 10000, 50000],
        default: '50000+',
        output: { count: { $sum: 1 }, total: { $sum: '$totalCents' } },
      },
    },
  ])
  .toArray()

3. Running totals and moving averages with $setWindowFields

Just like SQL window functions (SUM() OVER (...)), $setWindowFields computes cumulative revenue across days without collapsing rows:

const cumulative = await db
  .collection('dailySales')
  .aggregate([
    {
      $setWindowFields: {
        sortBy: { day: 1 },
        output: {
          runningRevenueCents: {
            $sum: '$revenueCents',
            window: { documents: ['unbounded', 'current'] },
          },
        },
      },
    },
  ])
  .toArray()

4. Recursive trees with $graphLookup

If your categories collection stores { _id, name, parentId }, $graphLookup walks the entire parent/child hierarchy in one query without writing recursive loops in JavaScript!

5. Pipeline updates (referencing existing fields in an update)

Normal updateMany(filter, { $set: ... }) cannot reference another field on the same document. Wrap the update in an array [...] to run an aggregation pipeline update:

// Set discountedCents = totalCents * 0.8 across all pending orders
await db.collection('orders').updateMany(
  { status: 'pending' },
  [
    {
      $set: {
        discountedCents: { $round: [{ $multiply: ['$totalCents', 0.8] }, 0] },
      },
    },
  ],
)

Replication, write concerns, and sharding in plain English

Even if you use a managed host like MongoDB Atlas, understanding three cluster concepts saves you from nasty production surprises.

How replica sets keep your data safe

In production, never run a single standalone mongod node. Run a 3-node replica set (one Primary plus two Secondaries).

All writes hit the Primary, which records every change in a capped log called the oplog. Secondaries continuously tail the oplog and replay those writes within milliseconds. If the Primary crashes, the remaining two nodes hold an automatic election and promote a new Primary in a few seconds!

Write concerns (w: 'majority') and read preferences

  • w: 'majority' (the modern default) tells MongoDB not to confirm a write until a majority of replica-set nodes have written it to their journal. Even if the Primary loses power one millisecond later, your confirmed order is never lost!
  • Read from the Primary by default (readPreference: 'primary'). Beginners sometimes turn on secondaryPreferred hoping to speed up reads, then wonder why a user edits their profile, reloads the page, and sees their old name for half a second (replication lag!). Only send heavy background analytics reports to secondaries.

When do you actually need sharding?

Sharding splits one giant collection across multiple replica sets using a shard key. It adds serious operational complexity and cross-shard query overhead.

My honest advice: do not shard early. A single well-indexed replica set with enough RAM to hold your working set comfortably handles hundreds of gigabytes of data and thousands of queries per second. Always optimize ESR indexes and vertical hardware first.

Change Streams and real-time reactions

Need to send a welcome email, invalidate a cache, or push a live dashboard update whenever a document changes in MongoDB?

On a replica set (including MongoDB Atlas), Change Streams let your Node.js app subscribe to live insert, update, and delete events directly from MongoDB’s oplog:

const changeStream = db.collection('orders').watch(
  [{ $match: { operationType: 'insert' } }],
  { fullDocument: 'updateLookup' },
)

for await (const change of changeStream) {
  console.log('New order arrived:', change.fullDocument._id)
}

Every change event includes an _id resume token (change._id). Save that token periodically so if your Node.js worker restarts, you can pass { resumeAfter: lastToken } and pick up right where you left off without missing a single order.

Transactions and atomicity

Writes to a single document in MongoDB are always 100% atomic, even when modifying multiple nested fields and arrays inside that document at once.

That is why good schema design (embedding an order and its line items together) removes the need for multi-document transactions in 90% of routes.

When you genuinely must update two separate documents or collections as one all-or-nothing unit (like transferring money between two accounts or decrementing inventory while creating an order), use a multi-document ACID transaction (requires a replica set or MongoDB Atlas):

const session = client.startSession()

try {
  await session.withTransaction(async () => {
    const debit = await db.collection('accounts').updateOne(
      { _id: fromId, balanceCents: { $gte: amount } },
      { $inc: { balanceCents: -amount } },
      { session },
    )

    if (debit.modifiedCount === 0) {
      throw new Error('Insufficient funds')
    }

    await db.collection('accounts').updateOne(
      { _id: toId },
      { $inc: { balanceCents: amount } },
      { session },
    )
  })
} finally {
  await session.endSession()
}

Watch the single biggest transaction trap: you MUST pass { session } to every single query and update inside withTransaction(). If you forget { session } on one call, that write executes immediately outside the transaction and will NOT roll back if an error occurs!

Complete project: a production Express + MongoDB + Zod Bookstore API

Let’s tie everything together into a clean, runnable Express API using our official mongodb driver, $jsonSchema + ESR indexes initialized at startup, Zod 4 validation, ObjectId.isValid guards, keyset pagination, atomic updates, and an aggregation endpoint.

Create a new folder and install dependencies:

mkdir mongo-bookstore-api
cd mongo-bookstore-api
npm init -y
npm pkg set type=module
npm install express mongodb zod

1. Database setup (db.js)

// db.js
import { MongoClient } from 'mongodb'

const uri = process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017'
export const client = new MongoClient(uri, {
  maxPoolSize: 20,
  serverSelectionTimeoutMS: 5000,
})

await client.connect()
export const db = client.db(process.env.MONGODB_DB || 'bookstore_api')

export async function ensureSchemaAndIndexes() {
  const existing = await db.listCollections({ name: 'books' }).toArray()
  if (existing.length === 0) {
    await db.createCollection('books', {
      validator: {
        $jsonSchema: {
          bsonType: 'object',
          required: ['title', 'category', 'pages', 'createdAt'],
          properties: {
            title: { bsonType: 'string', minLength: 1, maxLength: 160 },
            category: { enum: ['programming', 'infrastructure', 'ai'] },
            pages: { bsonType: 'int', minimum: 1 },
            tags: { bsonType: 'array', items: { bsonType: 'string' } },
            createdAt: { bsonType: 'date' },
          },
        },
      },
    })
  }

  const books = db.collection('books')
  await books.createIndex({ title: 1 }, { unique: true })
  await books.createIndex({ category: 1, createdAt: -1 })
}

export async function closeDb() {
  await client.close()
}

2. The Express API (server.js)

// server.js
import express from 'express'
import { ObjectId } from 'mongodb'
import { z } from 'zod'
import { closeDb, db, ensureSchemaAndIndexes } from './db.js'

await ensureSchemaAndIndexes()

const app = express()
app.use(express.json({ limit: '64kb' }))

const books = db.collection('books')

const CreateBookSchema = z.object({
  title: z.string().trim().min(1, 'Title is required').max(160),
  category: z.enum(['programming', 'infrastructure', 'ai']),
  pages: z.coerce.number().int().min(1).max(2000),
  tags: z.array(z.string().trim().min(1)).max(10).default([]),
})

const UpdateBookSchema = CreateBookSchema.partial()

// GET /books?category=programming&after=<ObjectId>&limit=20
app.get('/books', async (req, res, next) => {
  try {
    const filter = {}
    if (req.query.category) filter.category = String(req.query.category)
    if (req.query.after) {
      if (!ObjectId.isValid(String(req.query.after))) {
        return res.status(400).json({ error: 'Invalid after cursor' })
      }
      filter._id = { $lt: new ObjectId(String(req.query.after)) }
    }

    const limit = Math.min(Number(req.query.limit) || 20, 100)
    const items = await books
      .find(filter)
      .sort({ _id: -1 })
      .limit(limit)
      .toArray()

    const nextCursor = items.length === limit ? items.at(-1)._id : null
    res.json({ items, nextCursor })
  } catch (err) {
    next(err)
  }
})

// GET /books/stats
app.get('/books/stats', async (_req, res, next) => {
  try {
    const stats = await books
      .aggregate([
        {
          $group: {
            _id: '$category',
            count: { $sum: 1 },
            avgPages: { $avg: '$pages' },
          },
        },
        { $sort: { count: -1 } },
      ])
      .toArray()
    res.json({ stats })
  } catch (err) {
    next(err)
  }
})

// GET /books/:id
app.get('/books/:id', async (req, res, next) => {
  try {
    if (!ObjectId.isValid(req.params.id)) {
      return res.status(400).json({ error: 'Invalid book ID' })
    }
    const book = await books.findOne({ _id: new ObjectId(req.params.id) })
    if (!book) return res.status(404).json({ error: 'Book not found' })
    res.json(book)
  } catch (err) {
    next(err)
  }
})

// POST /books
app.post('/books', async (req, res, next) => {
  try {
    const parsed = CreateBookSchema.safeParse(req.body)
    if (!parsed.success) {
      return res.status(422).json({
        error: 'Validation failed',
        issues: parsed.error.issues,
      })
    }

    const doc = { ...parsed.data, createdAt: new Date() }
    const result = await books.insertOne(doc)
    res.status(201).json({ _id: result.insertedId, ...doc })
  } catch (err) {
    if (err.code === 11000) {
      return res.status(409).json({ error: 'A book with that title already exists' })
    }
    next(err)
  }
})

// PATCH /books/:id
app.patch('/books/:id', async (req, res, next) => {
  try {
    if (!ObjectId.isValid(req.params.id)) {
      return res.status(400).json({ error: 'Invalid book ID' })
    }
    const parsed = UpdateBookSchema.safeParse(req.body)
    if (!parsed.success) {
      return res.status(422).json({
        error: 'Validation failed',
        issues: parsed.error.issues,
      })
    }

    const updated = await books.findOneAndUpdate(
      { _id: new ObjectId(req.params.id) },
      { $set: { ...parsed.data, updatedAt: new Date() } },
      { returnDocument: 'after' },
    )
    if (!updated) return res.status(404).json({ error: 'Book not found' })
    res.json(updated)
  } catch (err) {
    if (err.code === 11000) {
      return res.status(409).json({ error: 'A book with that title already exists' })
    }
    next(err)
  }
})

// DELETE /books/:id
app.delete('/books/:id', async (req, res, next) => {
  try {
    if (!ObjectId.isValid(req.params.id)) {
      return res.status(400).json({ error: 'Invalid book ID' })
    }
    const result = await books.deleteOne({ _id: new ObjectId(req.params.id) })
    if (result.deletedCount === 0) {
      return res.status(404).json({ error: 'Book not found' })
    }
    res.status(204).end()
  } catch (err) {
    next(err)
  }
})

app.use((err, _req, res, _next) => {
  console.error(err)
  res.status(500).json({ error: 'Internal server error' })
})

const server = app.listen(3000, () => {
  console.log('Bookstore API listening on http://localhost:3000')
})

for (const signal of ['SIGINT', 'SIGTERM']) {
  process.on(signal, async () => {
    server.close()
    await closeDb()
    process.exit(0)
  })
}

Notice how we handle duplicate key error err.code === 11000 cleanly by returning 409 Conflict, validate every ObjectId before querying, and close both the HTTP server and MongoDB pool gracefully on shutdown.

Testing MongoDB apps cleanly with node:test and Docker

Mocking the MongoDB driver in unit tests hides real bugs: mocks never catch bad $jsonSchema rules, missing unique indexes, or broken aggregation pipelines.

Instead, run fast integration tests against a real local mongo:8 container on a dedicated test database (bookstore_test) that we wipe between tests:

// books.test.mjs
import assert from 'node:assert/strict'
import { after, before, beforeEach, describe, it } from 'node:test'
import { MongoClient } from 'mongodb'

const TEST_URI = process.env.MONGODB_TEST_URI || 'mongodb://127.0.0.1:27017'

describe('books collection', () => {
  let client
  let db
  let books

  before(async () => {
    client = new MongoClient(TEST_URI)
    await client.connect()
    db = client.db('bookstore_test')
    books = db.collection('books')
  })

  beforeEach(async () => {
    await db.dropDatabase()
    await books.createIndex({ title: 1 }, { unique: true })
  })

  after(async () => {
    await db.dropDatabase()
    await client.close()
  })

  it('inserts a book and rejects duplicate titles with code 11000', async () => {
    await books.insertOne({ title: 'MongoDB Handbook', pages: 42 })

    await assert.rejects(
      () => books.insertOne({ title: 'MongoDB Handbook', pages: 50 }),
      (err) => err.code === 11000,
    )
  })
})

In GitHub Actions CI, attach a real mongo:8 service container right in your workflow so every pull request runs your real database tests automatically:

services:
  mongodb:
    image: mongo:8
    ports:
      - 27017:27017

Production essentials: security, backups, monitoring, and migrations

Before you ship MongoDB to real users, build these five habits into your deployment checklist:

1. Lock down network access and authentication

Never expose port 27017 directly to the public internet. Bind mongod to 127.0.0.1 or a private VPC/Tailscale network, enable SCRAM authentication with strong per-app least-privilege users (readWrite on one database only, never root/admin), and require TLS for connections across networks.

2. Automate backups and actually test restoring them

A backup you have never restored is not a backup. On self-hosted servers, schedule compressed snapshots with mongodump and test restoring into a staging database with mongorestore:

mongodump --uri="$MONGODB_URI" --archive=bookstore-2026-12-03.gz --gzip
mongorestore --uri="$STAGING_URI" --archive=bookstore-2026-12-03.gz --gzip --drop

On MongoDB Atlas, enable automated continuous cloud backups with point-in-time recovery.

3. Monitor slow queries

MongoDB logs queries slower than 100 ms by default. You can also turn on the database profiler temporarily during load testing to inspect slow queries right inside system.profile:

db.setProfilingLevel(1, { slowms: 50 })
db.system.profile.find().sort({ ts: -1 }).limit(5)

Grab any slow query, run .explain('executionStats'), and add the missing ESR index.

4. Evolve schemas with zero downtime

Because MongoDB documents do not require ALTER TABLE locks, you can evolve schemas smoothly by stamping documents with schemaVersion: 2.

Your application reads both version 1 and version 2 cleanly on the fly, writes version 2 on every save, and an optional background script backfills old records in small batches (bulkWrite) with zero downtime.

5. Guard against NoSQL query injection

If you ever pass req.body or req.query straight into find(), an attacker sending { "email": { "$ne": "" }, "password": { "$ne": "" } } in JSON can bypass naive login checks!

Validating every request with Zod (z.string()) eliminates operator injection completely because Zod rejects any object where your schema expects a plain string.

Debugging common MongoDB mistakes

SymptomUsual causeFast fix
BSONError: input must be a 24 character hex stringPassed invalid URL param straight to new ObjectId()Check ObjectId.isValid(id) and return 400 first
Query is slow even with a compound indexIndex key order breaks ESR (Range before Sort)Reorder index keys to Equality -> Sort -> Range
findOneAndUpdate returns stale old valuesDefault returns the document before updatePass { returnDocument: 'after' }
Array filter matched the wrong documentsWrote separate dot-notation keys on an array of objectsWrap both conditions inside $elemMatch
Transaction did not roll back one writeForgot { session } on one operation inside withTransactionPass { session } to every single query and update
Node.js app runs out of connections or slows downCreated a new MongoClient per HTTP requestShare one long-lived MongoClient across the whole app
Insert fails with Document failed validation$jsonSchema had additionalProperties: false without _idInclude _id: { bsonType: 'objectId' } in properties
Duplicate insert crashes route with 500Unhandled unique index violation (err.code === 11000)Catch err.code === 11000 and return 409 Conflict

Quick reference: commands and operators

TaskCommand / Operator
Switch or create databaseuse bookstore
Insert one / manycol.insertOne(doc), col.insertMany(docs)
Query with projection & sortcol.find(filter, { projection }).sort({ createdAt: -1 }).limit(20)
Update specific fieldscol.updateOne(filter, { $set: { ... }, $inc: { ... } })
Update and return new doccol.findOneAndUpdate(filter, update, { returnDocument: 'after' })
Batch mixed writescol.bulkWrite(ops, { ordered: false })
Delete matching docscol.deleteOne(filter), col.deleteMany(filter)
Create ESR compound indexcol.createIndex({ eqField: 1, sortField: -1, rangeField: 1 })
Create auto-expiring TTL indexcol.createIndex({ expiresAt: 1 }, { expireAfterSeconds: 0 })
Verify index usagecol.find(...).explain('executionStats')
Run aggregation pipelinecol.aggregate([{ $match: ... }, { $group: ... }])
Stream large result setsfor await (const doc of col.find(...)) { ... }

Where to go from here

You now have a complete practical foundation in MongoDB, from your first mongosh insert through BSON types, array operators, shared Node.js connection pools, embedding vs referencing, $jsonSchema validation, ESR compound indexes, aggregation pipelines, Change Streams, ACID transactions, and production backups.

If you want to compare document databases with relational SQL databases or sharpen your backend skills, check out my free SQL Handbook, PostgreSQL Handbook, and Node.js Handbook.

Want me to talk about your product? You can sponsor this site.

Related posts about database: