Document database

On this page 7

A document database is a database that stores data as self-describing documents, typically in JSON or a binary form of JSON such as BSON, and lets applications query the fields inside those documents. Among database models in databases, it belongs to the NoSQL family and sits between the simple key-value store and the strictly tabular relational model.

Each document holds a complete record with nested objects and arrays, so an order can contain its line items and shipping address in one unit. Well-known implementations include MongoDB, Couchbase, Amazon DocumentDB, Azure Cosmos DB and Apache CouchDB, while PostgreSQL with the `jsonb` type offers document features inside a relational engine.

How a document database organizes data

Documents are grouped into collections, which play a role similar to tables but do not enforce one fixed set of columns. Every document has a unique primary key, such as the _id field in MongoDB, and may contain scalar values, nested sub-documents and arrays of values or objects.

The database understands the internal structure of each document. It can index a nested field such as customer.address.city, filter on array elements and return only selected fields. This is the decisive difference from a key-value store, which treats the stored value as an opaque blob that can only be fetched by its key.

The model is often called schema-flexible rather than schemaless. The structure still exists, but it lives in the application code and optional validation rules instead of a mandatory table definition. MongoDB, for example, supports JSON Schema validation on a collection to reject documents with missing or mistyped fields.

The following table maps relational vocabulary to the corresponding document database concepts.

Relational conceptDocument database conceptNote
TableCollectionNo fixed column list
RowDocumentCan contain nested objects and arrays
ColumnFieldMay differ between documents
JoinEmbedding or lookupEmbedding avoids joins at read time
Foreign keyReference by IDUsually not enforced by the engine
Relational and document terminology

Embedding versus referencing

Data modeling in a document database is driven by access patterns, not by normalization rules. The central design choice is whether related data is embedded inside one document or stored separately and referenced by its identifier.

SituationRecommended approachReason
Data read together every timeEmbedOne read returns the whole entity
One-to-few relationshipEmbedSmall, bounded arrays stay efficient
One-to-many with unbounded growthReferenceAvoids hitting the document size limit
Data shared by many parentsReferenceAvoids duplicating values that change
Frequently updated child itemsReferenceAvoids rewriting a large parent document
Choosing between embedding and referencing

Embedding gives fast single-read access and atomic updates of the whole aggregate, because single-document writes are atomic in practically every document engine. The price is duplication: if a product name is copied into thousands of orders, renaming the product means updating thousands of documents or accepting stale copies.

Size limits make the choice concrete. A MongoDB document cannot exceed 16 MB, and Azure Cosmos DB limits items to 2 MB. An embedded array of comments that grows without bound will eventually break, so unbounded growth is a strong signal to reference instead.

Document databases compared with other models

The document model is one of several NoSQL models, and each serves a different shape of data. Graph, time-series and vector databases cover the remaining specialized cases in the same topic.

ModelBasic unitStrongest useTypical weakness
RelationalRow in a fixed tableComplex joins and strict integrityRigid schema changes
DocumentNested JSON-like documentAggregates read as a wholeCross-document joins and constraints
Key-valueOpaque value under a keyCaching and session storageNo queries on value content
GraphNodes and edgesDeep relationship traversalBulk aggregation over all records
Time-seriesTimestamped measurementMetrics and sensor dataGeneral business entities
VectorEmbedding vectorSimilarity searchExact transactional records
Document database in the landscape of database models

The boundary with relational systems has blurred considerably. PostgreSQL jsonb with GIN indexes and MySQL’s JSON type provide document storage inside relational engines, while MongoDB has supported multi-document ACID transactions since version 4.0. The choice is therefore less about capability and more about which model is native to the workload.

Querying, indexing and scaling

Document databases provide their own query languages rather than standard SQL. MongoDB uses a JSON-based query syntax and an aggregation pipeline, Couchbase uses SQL++ (formerly N1QL), and CouchDB relies on map-reduce views and the Mango query interface.

Indexing works on fields at any depth. Compound indexes cover several fields, multikey indexes index every element of an array, and text or geospatial indexes support specialized searches. Without a suitable index, a query performs a full collection scan, which is the most common cause of slow queries in this model.

Most document databases scale out through sharding, which distributes documents across nodes by a shard key. A good shard key has high cardinality and spreads writes evenly; a monotonically increasing key such as a timestamp sends all new writes to one shard and creates a hot spot. Replication with automatic failover provides availability, with tunable read and write concerns controlling the trade-off between latency and durability.

Limitations and common pitfalls

Schema flexibility shifts responsibility to the application. Typical problems include the following:

  • Schema drift: documents written by different application versions accumulate inconsistent field names and types.
  • Relational data forced into documents: many-to-many relationships lead to heavy duplication or slow application-side joins.
  • Oversized documents: large arrays make every update rewrite and replicate much more data than necessary.
  • Missing indexes on filter fields, which turns routine queries into full collection scans.
  • Poor shard key choice, which is difficult and costly to change once the cluster holds production data.

The model fits best when the application works with self-contained aggregates such as user profiles, product catalogs, content items or orders. It fits poorly when the core of the workload is ad hoc reporting across many entity types with strict referential integrity.

Understanding it simply

A document database stores information the way a filing cabinet stores folders. Each folder holds everything about one thing, such as a customer with their addresses and orders, instead of spreading the pieces across many separate lists.

Folders do not all need the same layout, so adding a new kind of detail is easy. The trade-off is that when the same detail appears in many folders, someone must keep all those copies up to date.

Applied in practice

An online marketplace sells about 200,000 products in categories as different as shoes, laptops and garden furniture. Shoes need sizes and materials, laptops need processor and memory details, and furniture needs dimensions. In a relational design, these varying attributes would require many sparse columns or a complex attribute table.

The team stores each product as one document with common fields such as name, price and category, plus a nested attributes object specific to the category. A compound index on category and price supports the main listing pages, and a multikey index on tags supports filtering. Product pages now load with one read per product, and adding a new category with new attributes requires no schema migration. Orders and payments stay in a relational database, where strict transactional integrity matters most.