DEV Community

Cover image for Document Databases: How MongoDB Stores Data
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

Document Databases: How MongoDB Stores Data

In a relational database, a blog post with its tags and comments is spread over several tables: posts, tags, post_tags, comments. To show one page, you join them back together. Your application code, meanwhile, works with a single object: a post that has a list of tags and a list of comments. A document database removes that gap. It stores the object roughly as your code sees it, as one document.

MongoDB is the best-known document database. This article explains what a document is, how MongoDB stores and finds documents, and the main design decision you make with it: embed or reference.

What a document is

A document is a set of field and value pairs, like a JSON object. Values can be strings, numbers, dates, booleans, nested objects and arrays. Here is a blog post as one document:

{
  "_id": ObjectId("6750a1c2e4b0a1b2c3d4e5f6"),
  "title": "Indexes 101",
  "author": { "id": 42, "name": "Sara" },
  "tags": ["database", "performance"],
  "published_at": ISODate("2026-12-03T09:00:00Z"),
  "comments": [
    { "user": "amine", "text": "Clear, thanks", "at": ISODate("2026-12-03T10:15:00Z") }
  ]
}
Enter fullscreen mode Exit fullscreen mode

Documents live in collections, which play the role of tables. A collection does not force one schema: two documents in the same collection can have different fields. In practice, documents in a collection usually share a shape, and you can enforce one with schema validation (a $jsonSchema rule on the collection).

Every document has an _id field that is unique in its collection and acts as the primary key. If you do not set it, the driver generates an ObjectId: a 12-byte value that starts with a timestamp, so new ids roughly sort by creation time.

BSON: the format on disk and on the wire

MongoDB does not store JSON text. It stores BSON (Binary JSON), a binary encoding of the same structure. BSON adds things JSON lacks, such as real date types, 32-bit and 64-bit integers, decimals, binary data and ObjectId. It also stores length prefixes, so the server can skip over a field or a sub-document without parsing it.

Drivers convert between your language's objects and BSON. The same BSON is used on the network and in storage, so there is no translation step in between.

One hard limit to remember: a single BSON document can be at most 16 MB. Larger files go in GridFS or in object storage, with a reference in the document.

How documents reach the disk

MongoDB hands storage to a storage engine. The default one is WiredTiger. In broad strokes:

  1. Each collection and each index is stored as its own WiredTiger table, organized as a B-tree.
  2. A write goes first into memory (WiredTiger's cache) and into a journal, a write-ahead log on disk. Once the journal entry is durable, the write can be acknowledged, depending on the write concern you ask for.
  3. Periodically WiredTiger writes a checkpoint: a consistent snapshot of the data files. After a crash, MongoDB restarts from the last checkpoint and replays the journal.
  4. Data and indexes are compressed on disk by default, which matters because documents repeat field names in every record.
  5. Concurrency control works at the document level, so two clients writing different documents in the same collection do not block each other.

This design looks a lot like a relational engine underneath: B-trees, a write-ahead log, checkpoints, MVCC snapshots. The difference is the unit of data, which is a whole document instead of a flat row.

Finding documents: queries and indexes

You query with a filter document:

db.posts.find({ tags: "performance", "author.id": 42 })
        .sort({ published_at: -1 })
        .limit(10)
Enter fullscreen mode Exit fullscreen mode

Without an index, MongoDB scans every document in the collection (a collection scan). With an index, it walks a B-tree instead. Indexes work on any field, including nested ones (author.id) and arrays. An index on an array field is a multikey index: it holds one entry per array element, so tags: "performance" can use it.

db.posts.createIndex({ tags: 1, published_at: -1 })
Enter fullscreen mode Exit fullscreen mode

Compound indexes follow the same rules you know from SQL: field order matters, and the index helps queries that use a prefix of its fields. explain("executionStats") shows whether a query used an index (IXSCAN) or scanned the collection (COLLSCAN).

Embed or reference

This is the decision that shapes a MongoDB schema. The guiding rule is: data that is read together should be stored together.

Embed when the child data belongs to the parent and is read with it: an order and its line items, a user and their addresses, a post and its first few comments. One read returns everything, and a write to a single document is atomic, so the order and its lines always change together.

Reference when the related data is large, shared, or grows without limit: a product referenced by thousands of orders, or a post with hundreds of thousands of comments. You store the other document's _id and fetch it with a second query, or join it in an aggregation with the $lookup stage.

A common middle ground is to embed a small copy of the fields you display (the author's name) and reference the full record (the author's profile). The trade-off: if the author changes their name, you update it in several places.

Warning signs that you embedded the wrong thing:

  • An array grows forever (comments, events, log lines). Documents get larger, writes get slower, and you approach the 16 MB limit.
  • You keep updating the same embedded data in many documents.
  • You mostly query the child data on its own, without the parent.

Transactions and consistency

Because one document can hold a whole aggregate, many operations need only single-document atomicity, which MongoDB always provides. For changes across several documents, MongoDB supports multi-document ACID transactions on replica sets and sharded clusters. They work, but they cost more than single-document writes, so a schema that needs them everywhere is often a sign that the data would fit a relational model better.

Scaling out

For availability, MongoDB runs as a replica set: one primary takes writes, secondaries copy its operation log (the oplog) and can take over if the primary fails. For size, sharding splits a collection across several replica sets by a shard key. The shard key choice is important: a key that is always increasing, like a timestamp, sends all new writes to one shard.

Common mistakes

  • Treating "schemaless" as "no design". The schema lives in your code and your queries. Design it around how the app reads data, and add validation rules.
  • Modeling it like SQL. Splitting everything into small collections and joining with $lookup gives you a relational database without the relational optimizer.
  • Missing indexes. A slow query on a large collection is usually a COLLSCAN. Check with explain.
  • Unbounded arrays. Move fast-growing children into their own collection.

In short

A document database stores each record as a self-contained document, close to the object in your code. MongoDB keeps documents as BSON in collections, stores them through the WiredTiger engine with a journal, checkpoints and compression, and finds them with B-tree indexes, including multikey indexes on arrays. The core design skill is deciding what to embed and what to reference, based on how the data is read.

Watch the animated version: https://youtu.be/_SR236xAwdM


Originally published at abdeldjalilchougui.biz.

Top comments (0)