How MongoDB works
A database that stores JSON-like documents instead of rows and tables.
MongoDB stores flexible, JSON-like documents grouped into collections, encoded on disk as BSON. Every document carries a unique _id. Durability and availability come from replica sets (a primary plus secondaries with automatic failover), and horizontal scale comes from sharding data across nodes by a shard key. The document model shines when your data is naturally nested and your schema evolves fast.
Documents & collections
MongoDB stores data as documents — JSON-like objects with nested fields and arrays — and groups related documents into collections, the rough equivalent of tables. Unlike a relational row, a single document can hold an entire object graph, so a blog post can embed its author details and comments in one record. You read and write whole documents, which maps naturally onto how objects live in application code.
BSON & _id
On disk and over the wire, documents are encoded as BSON — a binary, length-prefixed form of JSON that is fast to traverse and adds richer types like dates, 64-bit integers, binary blobs, and ObjectId. Every document must have a unique _id field that serves as its primary key; if you don't supply one, MongoDB generates a 12-byte ObjectId that is roughly time-ordered. That _id is automatically indexed, so lookups by it are instant.
Sharding & shard key
To scale beyond one machine, MongoDB shards a collection: it splits documents across many nodes using a shard key you choose. A router process (mongos) inspects each query's shard key and directs it to the node holding the relevant range or hash bucket, so both storage and write throughput grow horizontally. Choosing a shard key with high cardinality and even access is critical — a poor one creates a hotspot that funnels traffic to a single shard.
Replica sets & failover
Each shard is backed by a replica set: one primary that accepts all writes and several secondaries that continuously copy the primary's operation log (oplog). If the primary becomes unreachable, the remaining members hold an election and automatically promote a secondary to primary, so the system keeps accepting writes without manual intervention. This replication is what gives MongoDB durability and high availability.
Indexes
By default only _id is indexed, so any other frequent query needs its own index to avoid scanning the whole collection. MongoDB supports single-field, compound, multikey (for arrays), text, and geospatial indexes, letting you tune for the exact query shapes your application runs. As with any database, indexes speed reads but add write cost and storage, so you index deliberately rather than everywhere.
When the document model fits
The document model is at its best when data is naturally hierarchical, read and written as a unit, and evolving quickly — product catalogs, user profiles, event payloads, and content management are classic fits. It struggles when data is highly relational with many-to-many links that force application-side joins, or when you need multi-document transactions everywhere. Match the model to your access patterns rather than defaulting to it.
Why the document model exists
Relational databases model the world as rows split across many normalized tables, and for decades that was simply how databases worked. But application developers spend most of their time working with objects — a user with an address and a list of orders — and reassembling those objects from a dozen joined tables on every request is tedious and sometimes slow. MongoDB, the most popular document database, was built around a different premise: store data in the shape your application actually uses it.
That shape is the document — a JSON-like structure with nested fields and arrays that can represent a whole object in one place. Instead of scattering a blog post across posts, authors, tags, and comments tables, you can store the post and everything it owns as a single document. The payoff is developer velocity and read locality: fetching one document returns the complete object, and there is no upfront schema migration ceremony when the data evolves. MongoDB exists to make that document-centric way of working the default rather than something you bolt onto a relational store.
Documents, collections, BSON, and _id
The building blocks are simple. A document is a set of key-value pairs where values can themselves be documents or arrays, giving you arbitrarily nested structure. Documents are grouped into collections, the loose analog of tables — except a collection imposes no fixed schema, so two documents in the same collection can have different fields. This flexible schema is MongoDB's signature trait: you can add a field to new documents without touching old ones or running a migration.
Under the hood, documents are stored as BSON (Binary JSON), a binary encoding that is faster for machines to parse and skip through than text JSON, and that supports richer types — native dates, 64-bit integers, decimal, binary blobs, and the ObjectId. BSON is length-prefixed, so the database can jump over fields it doesn't need without parsing them.
Every document carries a mandatory `_id` field that uniquely identifies it within its collection — this is its primary key. If you don't provide one, MongoDB assigns a 12-byte ObjectId that encodes a timestamp, a machine/process identifier, and a counter, making it globally unique and roughly sortable by creation time. The _id is automatically indexed, so retrieving a document by its id is always fast.
Replica sets and failover
A single database server is a single point of failure, so production MongoDB runs as a replica set — a group of nodes holding copies of the same data. Exactly one member is the primary, and it alone accepts writes. The other members are secondaries, and they continuously replicate the primary's changes by tailing its oplog (operation log), a rolling record of every write the primary applies.
The elegance is in what happens when the primary fails. The remaining members notice it has stopped responding (via heartbeats), hold an election, and promote one of the up-to-date secondaries to be the new primary — automatically, usually within seconds. Applications reconnect to the new primary and keep going. This automatic failover is what turns a fragile single server into a highly available system.
Replica sets also let you tune the durability/latency trade-off through write concern: you can require a write to be acknowledged by just the primary (fast, small risk) or by a majority of members (slower, safe from a single-node loss). Secondaries can additionally serve read traffic to spread load, at the cost of possibly returning slightly stale data because replication is asynchronous.
Sharding for horizontal scale
Replication gives you availability and read scaling, but every write still lands on one primary, and one machine can only hold so much data. To scale writes and storage horizontally, MongoDB uses sharding — partitioning a collection's documents across many shards, where each shard is itself a replica set.
The mechanism hinges on the shard key, a field (or fields) you designate to decide which shard a document lives on. MongoDB divides the key's value space into ranges or hash buckets and assigns them to shards. A routing process called mongos sits in front of the cluster: it reads a query's shard key and forwards the request only to the shard(s) that can satisfy it, so the cluster behaves like one logical database.
Choosing the shard key is the most consequential decision in a sharded deployment. A good key has high cardinality (many distinct values) and spreads both storage and access evenly. A poor key — say, a monotonically increasing timestamp, or a low-cardinality status field — sends most traffic to one shard, creating a hotspot that defeats the whole point of sharding. Worse, the shard key is hard to change after the fact, so it demands real forethought about your access patterns.
Indexes, trade-offs, and when it fits
Out of the box, only _id is indexed, so any other frequent query — find users by email, posts by tag — needs an explicit index or MongoDB will scan every document in the collection. It supports single-field and compound indexes, multikey indexes that index each element of an array, plus specialized text and geospatial indexes. As always, indexes accelerate reads but slow writes and consume space, so you add them to match real query shapes rather than sprinkling them everywhere.
MongoDB's honest trade-offs are worth stating. The flexible schema that speeds early development can become chaos without discipline, so teams often add schema validation later. Data duplicated across embedded documents must be updated in multiple places. And while modern MongoDB supports multi-document ACID transactions, leaning on them heavily is a sign your data might be more relational than document-shaped.
So when does the document model fit? When your data is naturally hierarchical and read or written as a whole (user profiles, product catalogs, IoT/event payloads, CMS content), when your schema is still evolving quickly, and when your access patterns rarely need to join many entities together. When your data is deeply relational with many-to-many relationships and strong transactional integrity across entities, a relational database like Postgres is usually the better fit. The skill is matching the model to how you actually read and write your data — not defaulting to documents because they feel easy at the start.
Data is stored as documents (JSON-like objects) grouped into collections — no fixed table schema required.
Documents are encoded as BSON, a binary form of JSON that adds types like dates, binary data, and ObjectId.
Every document has a unique _id field — an ObjectId by default — that acts as its primary key.
A replica set keeps synchronized copies on multiple nodes: one primary takes writes, secondaries replicate and can be auto-promoted on failure.
Sharding partitions a collection across many nodes by a shard key to scale writes and storage horizontally.
The document model fits nested, evolving data accessed as a whole; a bad shard key or heavy cross-document joins are its main pitfalls.
Quick quiz
What role does the primary play in a MongoDB replica set?
Why does choosing a good shard key matter so much?
Database types you should know
A field guide to the eight database families and when each one wins.
PostgreSQL 101
The relational database that quietly became everyone's default.
Comparing key-value stores
Four stores that all map keys to values — and almost nothing else in common.
Database index types
The data structures that turn a full-table scan into a pinpoint lookup.