AlgoViz

Document database

easy 25 min

A document database stores each thing as one self-describing document, such as a JSON object with nested objects and lists.

Video lesson · Chapter 1 of 5

Pack the order the way someone opens it

0:00 / 4:13

Document databases in 90 seconds

1:30Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

A document database keeps data as documents. A document is a set of named fields, and a field may hold a number, a text, a date, a list, or another small document. Formats such as JSON, BSON and XML all have this shape.

Documents live in collections, and every document has a unique identifier. Unlike a key-value store, the database can look inside the document: it can filter on a field, index it, and change a part of it.

Why it exists

Programs work with objects that contain lists and other objects. A table stores flat rows, so one order may be spread over four tables and put back together on every read. A document keeps the order in one piece.

Products also change. A book has an ISBN and a film has a duration. With documents, each can have its own fields without a migration. The price is that the application must now decide which shapes it accepts.

A short history

  1. 2005

    Damien Katz, a former Lotus Notes developer, starts CouchDB: JSON documents, reached over HTTP, made to synchronise between machines. It becomes an Apache project in 2008.

  2. February 2009

    The company 10gen releases MongoDB, which stores documents in a binary form called BSON.

  3. December 2014

    PostgreSQL 9.4 adds the jsonb type with indexing, so a relational table can hold documents too.

  4. December 2017

    RFC 8259 is published as the current Internet Standard for JSON, the text format most document databases speak.

Words to know

Document
One record made of named fields, which may be nested.
Collection
A group of documents, similar to a table, without one fixed set of columns.
Field
One name and its value inside a document.
BSON
Binary JSON: a binary format with extra types such as dates and binary data.
Embed
Store related data inside the same document.
Reference
Store only the identifier of another document.
Aggregation pipeline
A list of stages, each taking documents in and passing documents on.
Multikey index
An index with one entry for every element of a list.

Understand it

Start here

A folder for every pet

Imagine a vet that keeps one scrapbook folder for each pet. Everything about that pet is inside. A parrot's folder has a page for its wings and a dog's folder does not, and nobody minds.

The vet's folders
One folder for one petBISCUITDog, 4 yearsOwner: AshaVaccine: MarchVaccine: June

A cupboard where each folder may look different is easy to fill. Knowing what to put in the folder is the skill.

The idea

A row and a document

Document: only what exists

  • Jo has a name and an email, so those are the only two fields.
  • Jane also has a phone and a list of tags.
  • The list sits inside the document.
  • A new field needs no change to other documents.

Row: the same columns for all

  • Columns: id, name, email, phone, address.
  • Jo has no phone and no address, so both cells are NULL.
  • A list of tags needs a second table.
  • A new column is a schema change for the whole table.

Neither is wrong. Equal columns are exactly what you want when every record really has the same shape. Read SQL databases for that side.

  • Self-describing

    Each document carries the names of its fields along with the values.

  • Schema flexible

    Fields can vary between documents of one collection.

  • Nested

    A field can be a list or another document, to a limited depth.

  • Close to your code

    The stored shape is the shape of the object in the program.

Application, database, collections

An app server outside the database sends an insert or a query to a document database. Inside it, three collections named users, orders and products each hold documents. A copy of the data flows to a replica.
The database holds collections, and each collection holds documents. The second machine keeps a copy.

The four levels

These are MongoDB's names. A collection plays the part of a table.

Structure

What a document looks like

This order is one document. It embeds the customer, nests an address inside that, and holds a list of items and a list of tags. The total is 2×29.99+49.99=109.972 \times 29.99 + 49.99 = 109.97.

JavaScript
{  "_id": ObjectId("507f1f77bcf86cd799439011"),  "orderNumber": "ORD-2024-001",  "customer": {                     // embedded document    "name": "Jo Doe",    "email": "jo@example.com",    "address": {                    // nested again      "street": "123 Main St", "city": "NYC", "zip": "10001"    }  },  "items": [                        // list of documents    { "sku": "ITEM-001", "qty": 2, "price": 29.99 },    { "sku": "ITEM-002", "qty": 1, "price": 49.99 }  ],  "status": "shipped",  "total": 109.97,  "tags": ["priority", "express"],  // list of strings  "createdAt": ISODate("2024-01-15T10:30:00Z"),  "metadata": { "source": "mobile-app", "campaign": "winter-sale" }}
Real money is safer as whole cents or a decimal type; a floating point number cannot hold 0.1 exactly.

JSON and BSON

JSONBSON
FormText people can readBinary
TypesString, number, boolean, null, array, objectAdds dates, ObjectId, binary data, 32 and 64 bit integers, decimals
Example fields_id: "user123", age: 28, active: true_id: ObjectId, created: ISODate, data: BinData
Found inCouchDB, and the jsonb type of PostgreSQL accepts itMongoDB
DynamoDB also stores documents, in its own attribute format and up to 400 KB an item.

BSON types you meet every day

TypeExampleNote
String"hello"UTF-8 text
Int32, Int6442Whole numbers
Double3.14159Floating point
BooleantrueOr false
ObjectId12 bytesStarts with a 4-byte time in seconds
DateISODate()A moment in time
Array[1, 2, 3]A list
Object{ nested }A document in a document

Writing

What happens on an insert

One insert

With a majority write concern, the answer waits until enough members have the change.
  1. 1

    Receive the document

    The application sends it. The driver encodes it as BSON.

  2. 2

    Give it an identifier

    If _id is missing, an ObjectId is made, normally by the driver.

  3. 3

    Validate

    If the collection has validation rules, the document must pass them. By default a document that fails is rejected.

  4. 4

    Write it

    The document goes to the collection, and the change goes to the log that replicas read.

  5. 5

    Update indexes

    Every index on the collection gets its entries. More indexes make inserts slower.

  6. 6

    Acknowledge

    The application learns that the write is safe at the level it asked for.

Reading

Queries and operators

The four basic operations

JobMongoDB shellWhat it does
CreateinsertOne, insertManyAdds one document or a list
Readfind, findOneFilters, for example age above 18
UpdateupdateOne, updateManyChanges fields, for example pending becomes active
DeletedeleteOne, deleteManyRemoves matches, for example last login before a date

Query operators

GroupOperatorsMeaning
Comparison$eq, $neEqual, not equal
Comparison$gt, $gte, $lt, $lteGreater, at least, less, at most
Comparison$inOne of these values
Logical$and, $orAll conditions, any condition
Logical$not, $norNegate one, none match
Array$all, $sizeContains all of these, has this length
Array$elemMatchOne element meets all the conditions

How a find runs

A cursor streams results in batches, so the application does not have to hold them all.

Indexes

Finding documents fast

Without an index, the database reads every document. Most document indexes are B-trees, and they can point at nested fields and list elements.

IndexDefinitionFor
Single field{ email: 1 }Login by email. Add unique to forbid duplicates
Compound{ customer: 1, date: -1 }One customer's orders, newest first
Multikey{ tags: 1 } on a listFind by any element. Made automatically
Text{ content: "text" }Simple word search
Geospatial{ loc: "2dsphere" }Places near a point
TTL{ createdAt: 1 }, expire after 30 daysDelete old sessions on their own
The TTL task runs about every 60 seconds, so documents can live a little longer. For serious word search, use full-text search.

Analysis

The aggregation pipeline

An aggregation sends documents through stages. Each stage takes documents in and passes documents on, like a line of workers.

Five common stages

Put the filter first. It can use an index, and every later stage then has less to do.
JavaScript
// Orders of 2024, by status, most common firstdb.orders.aggregate([  { $match: { year: 2024 } },  { $group: { _id: "$status", count: { $sum: 1 } } },  { $sort: { count: -1 } }])

A related stage, $lookup, is a left outer join to another collection. So joins exist. They are a tool for the exception. If most of your reads need one, the data may belong in tables. Reports over years of data belong in an OLAP system.

Modeling

Embed or reference

Embed

  • A single read gets all the data
  • An update inside the document is atomic
  • Costs: copies of shared data
  • Costs: MongoDB allows 16 MiB a document
  • Best for one to one and one to few

Reference

  • Benefit: each fact is stored once
  • Benefit: documents stay small
  • Costs: more queries, or a $lookup
  • Costs: changes over several documents need a transaction
  • Best for one to many and many to many

Four questions

Embed what is read together, rarely changes and is bounded. Reference what is read alone, changes often or is unbounded.

How many comments fit in one post?

16×10242 bytes200 bytes per comment=16,777,216200≈83,886\frac{16 \times 1024^2\ \text{bytes}}{200\ \text{bytes per comment}} = \frac{16{,}777{,}216}{200} \approx 83{,}886
The 200 bytes are an assumption. You would feel pain far earlier: every read of the post would carry every comment.

The price of a copy

writes to change one shared fact=number of documents that embed it\text{writes to change one shared fact} = \text{number of documents that embed it}
A customer name embedded in 300 orders needs 300 updates. For an invoice that is right: it should keep the old name.

Patterns

Four modeling patterns

  • Bucket

    Group many small events. One document for sensor temp-1 on 15 January holds the readings 10:00 is 22 and 10:05 is 23.

  • Polymorphic

    Different shapes in one collection: a book with an ISBN, a film with a duration of 120, a game for PC. A type field says which.

  • Computed

    Store the answer and update it on write: 1,523 reviews and an average of 4.7 beside the product.

  • Subset

    Embed only the part that is shown: the last 10 reviews, with a reference to the full list.

The bucket pattern saves identifiers and index entries. A reading every 5 minutes is 24×12=28824 \times 12 = 288 readings a day. One bucket a day turns 288 documents into one, and one index entry instead of 288.

Schema

Flexible does not mean absent

If the database accepts any shape, then every reader has to handle every shape ever written. Two habits keep this under control: validation rules in the database, and a schema version field in the document.

Adding a field to millions of documents

WayHowGood when
Default on readCode treats a missing field as a defaultThe default is simple and permanent
Upgrade on readRead version 1, write back version 2Old documents are touched often
BatchA background job rewrites old documents slowlyYou want to delete the old code

Scale

Replicas and shards

A replica set keeps copies of the data so that another member can take over. Sharding splits a collection over machines by a shard key. A query that contains the shard key goes to one shard; a query without it has to ask all of them.

A query with the shard key

An app server asks a query router. The router sends the orders of customer 42 only to shard B. Shards A, B and C are separate boxes, and each holds its own range of customers.
All orders of one customer live together, so this question needs one shard.

Products

Popular document databases

MongoDBCouchDBAmazon DocumentDB
FormatBSONJSONBSON, through the MongoDB API
QueryRich query language, aggregation pipelineMango queries, MapReduce viewsCompatible with MongoDB APIs 3.6, 4.0, 5.0 and 8.0
ReplicationReplica sets, plus shardingMulti-master, any copy accepts writesManaged by AWS, storage grows on its own
SpecialChange streams, Atlas managed cloudHTTP API, offline-first with PouchDBMulti-AZ service agreement of 99.99%
Best forGeneral use: content, catalogues, mobile backends, IoTOffline apps, edge sites, decentralised syncTeams that live in AWS
Compatible with an API does not mean identical: check the list of supported operators before you move.

Summary

The whole topic in one minute.

A document database stores whole objects: fields, lists and nested objects together, under one identifier. Reading one document is one lookup, and a change inside one document is atomic.

The main decision is embed or reference. Embed what is read together, changes rarely and stays small. Reference what is shared, changes often or grows without end. A flexible schema does not remove the schema; it moves it into your code and your validation rules.

  • A document is one self-describing object with nested fields.
  • One document is read in one lookup and changed atomically.
  • Embed what is read together and bounded; reference what is shared, busy or unbounded.
  • The schema still exists: in your code and in validation rules.
  • Index the fields you filter on, and choose a shard key that your queries contain.

Sources