See It Flow
Interactive guide · 9 chapters · ~27 min read

MongoDB Fundamentals

What MongoDB is, why document databases exist, and how collections, documents, BSON, indexes, the aggregation pipeline, replication, and sharding fit together — the mental model every deeper MongoDB topic builds on.

Mangesh MandlikLast updated:
01 · Foundations

What is MongoDB?

MongoDB is a document-oriented NoSQL database — a server process that stores flexible, JSON-like documents grouped into collections, instead of rows in rigid tables.

MongoDB organizes data into collections made of documents, each document living inside a database. Every document is stored as BSON — a binary superset of JSON that adds types like dates, binary data, and 64-bit integers. There is no fixed schema enforced by default: two documents in the same collection can have entirely different fields.

ClientJSONmongodIndexCollectionBSONon disk
The path a write takes: application document → mongod → index lookup → collection → BSON on disk.

MongoDB Architecture: mongod, Collections, and Scale-Out

The diagram above traces the core of the architecture: the mongod server process stores BSON documents in collections inside databases, using indexes and a query planner to find them. For availability and scale, replica sets keep copies of the data on several servers and sharding spreads a collection across many, with mongos routing requests — both covered in later chapters.

Why use a document database at all

Natural object mapping

A document mirrors how an application already thinks about an object — nested fields and arrays map directly to JSON, with no object-relational mapping layer required.

Schema flexibility

New fields can be added to some documents without an ALTER TABLE-style migration or downtime — useful for evolving products and heterogeneous data.

Horizontal scalability

MongoDB has native sharding built in — distributing a collection across many servers as data and traffic grow, without bolting on an external sharding layer.

Powerful aggregation

The aggregation pipeline expresses filtering, joins, grouping, and reshaping as a sequence of composable stages, all executed inside the database.

Interactive

Visual Learning

Watch one MongoDB deployment handle documents, indexing, transactions, replication, and sharding as a single continuous system — not fifteen separate explanations.

02 · The data model

Collections, Documents, and _id

A MongoDB database is a set of collections, each holding documents that don't need to share the same shape.

Collection

A named group of documents, roughly analogous to a SQL table — but without an enforced column schema.

Document

A single record, stored as BSON — MongoDB's binary JSON. Documents can nest objects and arrays arbitrarily deep, up to a 16 MB document size limit.

_id field

Every document has a unique _id field, indexed automatically. If you don't supply one, MongoDB generates an ObjectId — a 12-byte value made of a 4-byte timestamp, a 5-byte per-process random value, and a 3-byte incrementing counter.

03 · Physical layout

How Data is Stored — BSON

Documents aren't stored as text — they're encoded as BSON, a binary format designed for fast traversal and rich types.

Doc 1Doc 2Doc 3
Collections hold BSON documents. Each document can have its own set of fields, sizes, and nested structures.

BSON adds types JSON lacks natively — dates, binary data, ObjectId, and distinguishes integers from floating-point numbers. This makes it faster to parse and more precise than storing JSON as plain text, at the cost of slightly larger size for some values.

04 · Speed

Indexes — Why Queries Get Fast

An index is a separate, ordered data structure that lets MongoDB jump straight to the documents a query needs, instead of scanning every document in a collection.

root<500k≥500kleafdoc-2leafdoc-5leafdoc-8leafdoc-11
A B-Tree index: a handful of comparisons narrow a million documents down to one.

The default index type is a B-Tree, just like in relational databases — a balanced tree where leaf entries point at documents. Looking up a value takes O(log n) comparisons instead of the O(n) documents a collection scan (COLLSCAN) requires.

Single-field index

The most common case — an index on one field, such as email or created_at.

Compound index

An index on multiple fields, e.g. { customer_id: 1, created_at: -1 } — field order determines which query shapes it can serve.

Multikey index

Automatically created when you index a field that holds an array — one index entry per array element.

05 · Under the hood

Query Execution — The Query Planner

Every query travels through a query planner before a single document is examined.

Query planner

Given a filter, evaluates candidate plans — collection scan vs one or more available indexes — and caches the winning plan's shape for similar future queries.

COLLSCAN

No usable index; MongoDB examines every document in the collection. Shows up in explain() output as the plan's stage.

IXSCAN

An index is used to narrow down candidate documents before fetching them — dramatically fewer documents examined for selective queries.

06 · Analytics

The Aggregation Pipeline

The aggregation pipeline is MongoDB's answer to complex analytical queries — a sequence of stages, each transforming the documents flowing through it.

documentscollection$match$group$sort$project
Documents flow through $match → $group → $sort → $project, each stage narrowing or reshaping the data.

$match

Filters documents early — placing it first lets MongoDB use an index and shrinks data flowing through later stages.

$group

Groups documents by a key and computes aggregates like $sum, $avg, $max within each group.

$sort / $project

$sort orders the results; $project reshapes each document's fields, including renaming and computing new ones.

07 · Reliability

Replication — Replica Sets

A replica set is a group of mongod processes maintaining the same data set — the foundation of MongoDB's high availability.

Primaryoplog writerSecondary Areplays oplogSecondary Breplays oplogElectedpromoted on failover
A primary accepts writes and streams its oplog to secondaries. If the primary fails, an election promotes a secondary.

Primary

The only member that accepts writes. All changes are recorded in its operation log (the oplog).

Secondary

Continuously replays the primary's oplog to stay in sync. Can optionally serve reads.

Election

If the primary becomes unreachable, remaining members vote and promote the most up-to-date secondary — automatically, with no external tool required.

08 · Scale

Sharding — Scaling Beyond One Server

Sharding distributes a collection's documents across multiple servers, so no single machine has to hold or serve all the data.

Clientmongosrouterconfig serverShard 1A–MShard 2N–Z
mongos routes each operation using the shard key and the config server's chunk map. Shards hold disjoint ranges of data.

Shard key

The field (or fields) used to distribute documents across shards. Chosen when the collection is sharded and hard to get right: changing it later means refining it (refineCollectionShardKey, MongoDB 4.4+) or resharding the collection (reshardCollection, 5.0+), both heavier operations than picking well up front. (Individual documents' shard key values can usually be updated (MongoDB 4.2+), except _id, but only through mongos and with the full shard key in the filter.)

mongos

The query router that applications actually talk to. It doesn't store data itself — it routes each operation to the right shard(s).

Config servers

Store the cluster's metadata — which shard key ranges (chunks) live on which shard.

09 · Durability & transactions

Durability, Journaling & Transactions

A replica set tells you *where* data is copied; this chapter covers what a single mongod does to make an acknowledged write survive, and what MongoDB guarantees when one logical operation touches several documents.

WiredTiger journal and checkpoints

WiredTiger, the default storage engine, keeps its working set in an in-memory cache and persists changes two ways. The journal is a write-ahead log: each write is recorded there first, and by default journal records are flushed to disk about every 100 ms (or immediately when a write asks for journal acknowledgment, j: true). Checkpoints write a consistent snapshot of the data files roughly every 60 seconds. After a crash, mongod starts from the last checkpoint and replays the journal to recover writes made since — so recovery depends on what reached the durable journal; journal commit intervals describe normal synchronization behavior, not a universal maximum data-loss guarantee, and actual durability depends on write concern, journaling settings and failure conditions. With the default writeConcernMajorityJournalDefault: true, a w: majority write is not acknowledged until it has reached the journal on a majority of members (deployments with voting in-memory members differ).

Single-document atomicity

Any write to one document — including updates to its embedded arrays and sub-documents — is atomic, with no transaction needed. That is the main reason MongoDB schema design favours embedding data that changes together: one document write replaces what a relational model would do with a multi-table transaction.

Multi-document transactions

For operations that must span documents or collections, MongoDB offers ACID transactions: on replica sets since 4.0, and on sharded clusters since 4.2. A transaction commits atomically. Applications can configure transaction-level read concern and write concern to match their consistency and durability requirements; snapshot reads and majority-acknowledged commits are explicit choices, not unconditional behavior: readConcern: "snapshot" gives the transaction a consistent snapshot, and writeConcern: { w: "majority" } is the usual commit setting so the commit survives a primary failover (the example below sets both explicitly). If another operation modifies a document the transaction has touched, the transaction aborts with a write conflict and the application must retry (drivers label these errors TransientTransactionError; the driver's callback API, e.g. withTransaction, retries for you).

javascriptTransfer between two accounts with the Node.js driver's callback API
const session = client.startSession();
try {
  await session.withTransaction(async () => {
    const accounts = client.db('bank').collection('accounts');
    await accounts.updateOne({ _id: 'A' }, { $inc: { balance: -100 } }, { session });
    await accounts.updateOne({ _id: 'B' }, { $inc: { balance: 100 } }, { session });
  }, {
    readConcern: { level: 'snapshot' },
    writeConcern: { w: 'majority' },
  });
} finally {
  await session.endSession();
}
Key takeaways
  • MongoDB stores flexible, JSON-like documents as BSON, grouped into collections without an enforced schema by default.
  • B-Tree indexes turn O(n) collection scans into O(log n) lookups — at the cost of slower writes.
  • The aggregation pipeline expresses filtering, grouping, and joins ($lookup) as composable stages.
  • Replica sets provide automatic failover — no external orchestrator needed, unlike many relational setups.
  • Sharding scales writes and storage horizontally, routed by mongos using a carefully chosen shard key.
  • Durability comes from the WiredTiger journal plus periodic checkpoints, and from write concern majority for failover safety; single-document writes are atomic, and multi-document transactions are available but time-limited (60 s by default) and costlier.