- Chapter
- Chapter 2 — Document Databases
- Prerequisites
- Chapter 1
- You will be able to
- Explain JSON and BSON and the type system of document databases, design documents as aggregates with correct types for money, time and identifiers, organise collections and apply schema validation, map documents to Java records and classes, and compare the document model with relational rows and JSONB
- Covers
- JSON/BSON; Documents; Collections
On this page
- 1. Concept / Definition
- 2. Why It Exists
- 3. Core Concepts
- 4. How It Works Internally — Storage of Documents
- 4A. Deep Dive — Document Model vs PostgreSQL JSONB
- 5. APIs / Features / Syntax
- 6. Practical Examples
- 7. Common Problems & Mistakes
- 8. Performance & Production Considerations
- 9. Architecture & Design Considerations
- 10. Interview Questions & Answers
1Concept / Definition
The document model stores data as self-describing, hierarchical records — documents — grouped into collections.

| TOC term | Definition |
|---|---|
| JSON / BSON | JSON is a text format for objects and arrays; BSON is MongoDB's binary encoding of JSON-like documents with additional types (Date, Decimal128, ObjectId, Binary) |
| Documents | Records of field–value pairs where values may be scalars, nested documents or arrays; each has a unique _id |
| Collections | Named groups of documents, analogous to tables but without a fixed column set (optionally validated) |
2Why It Exists
Object-oriented applications work with nested objects; relational storage splits them across tables (Volume III, impedance mismatch). Document databases store the object shape directly, removing joins for common reads and allowing heterogeneous records to coexist. JSON's ubiquity in web APIs made documents a natural fit.
The model also suits data whose shape varies between records and over time. Product catalogues, content blocks, IoT payloads and partner messages differ by type and evolve constantly; in a relational schema each variant means new nullable columns, extra tables or a migration on a large table. A document collection can hold old and new shapes side by side while the application upgrades them gradually, guided by a schema version field. Horizontal scale was the other driver: because an aggregate lives in one document, it can be placed on one shard by its shard key, and most reads and writes touch a single node without distributed joins. The price is that relationships between aggregates are no longer enforced by the database, so the flexibility only pays off when document boundaries match the application's access patterns and validation keeps types consistent.

3Core Concepts
3.1 JSON/BSON


| Pitfall | Consequence | Correct type |
|---|---|---|
| Money as double | Rounding errors (0.1 + 0.2) | Decimal128 ↔ BigDecimal |
| Dates as strings | Wrong sorting, no range queries by time zone | Date ↔ Instant |
| Numeric ids as strings sometimes, numbers other times | Queries miss documents ("17" ≠ 17) | One consistent type |
| UUID legacy binary subtypes | Cross-driver incompatibility | UuidRepresentation.STANDARD |
{ "_id": { "$oid": "66f3a1c2e4b0a91d2c7f0e11" },
"total": { "$numberDecimal": "4500.00" },
"placedAt": { "$date": "2026-09-25T10:15:00Z" },
"qty": { "$numberInt": "2" } }Extended JSON (above) shows BSON types explicitly in text form — useful in tooling and tests.
3.2 Documents

| Document rule | Detail |
|---|---|
_id | Required, unique per collection, immutable; default ObjectId (sortable by creation time) |
| Size | ≤ 16 MB (BSON); design well below (typically < 1 MB, ideally KBs) |
| Field names | Case-sensitive; $ and . restricted; keep short but meaningful |
| Nesting | Up to 100 levels; paths addressed with dot notation (name.first) |
| Arrays | Ordered; indexable (multikey); avoid unbounded growth |
| Atomicity | Writes to one document are atomic, including nested arrays |
3.3 Collections
| Collection feature | Use |
|---|---|
Schema validation ($jsonSchema) | Enforce required fields, types, enums |
| Capped collections | Fixed-size, insertion-ordered (logs) |
| Time series collections | Optimised storage for measurements |
| Clustered collections | Documents stored in _id order |
| TTL indexes | Automatic expiry |
| Views | Read-only aggregation-defined collections |
db.createCollection("orders", {
validator: { $jsonSchema: {
bsonType: "object",
required: ["customerId", "status", "total", "placedAt", "lines"],
properties: {
status: { enum: ["NEW", "PAID", "SHIPPED", "CANCELLED"] },
total: { bsonType: "decimal", minimum: 0 },
placedAt: { bsonType: "date" },
lines: { bsonType: "array", minItems: 1, maxItems: 200 }
} } },
validationLevel: "strict", validationAction: "error"
});4How It Works Internally — Storage of Documents
| Layer | MongoDB (WiredTiger) |
|---|---|
| Record | BSON document stored in a B-tree keyed by internal record id (or _id for clustered) |
| Compression | Snappy (default), zstd or zlib per collection; prefix compression for indexes |
| Concurrency | Document-level optimistic concurrency (write conflicts retried internally) |
| Updates | In-memory updates; checkpoints every 60 s; journal (WAL) for durability |
| Indexes | Separate B-trees mapping keys → record ids |
| BSON encoding detail | Benefit |
|---|---|
| Length prefixes on documents/strings | Skip fields without parsing |
| Type bytes | Typed comparisons and indexes |
| Field names stored per document | Flexibility — but repeated names cost space (compression helps) |
4ADeep Dive — Document Model vs PostgreSQL JSONB
| Aspect | MongoDB documents | PostgreSQL JSONB |
|---|---|---|
| Primary model | Documents everywhere | Relational with JSON columns |
| Types | Rich BSON types | JSON types (numbers, strings…) + SQL types around |
| Indexing | Any path, compound, multikey | GIN (containment), expression indexes on paths |
| Partial updates | $set, $push, array filters | jsonb_set (rewrites the value; TOAST) |
| Joins | $lookup (limited) | Full SQL joins |
| Scale-out | Native sharding | Partitioning; Citus for distribution |
| Best fit | Document-shaped domain at scale | Relational core with flexible attributes |

5APIs / Features / Syntax
| API | Purpose |
|---|---|
MongoClient, MongoDatabase, MongoCollection<T> | Driver entry points |
Document, BsonDocument | Generic document representations |
POJO/record codecs (PojoCodecProvider, automatic record support) | Typed mapping |
Spring Data @Document, @Id, @Field, @Indexed, @Version | Annotation mapping |
MongoCustomConversions | Custom type converters (value objects) |
db.createCollection(… validator …), collMod | Validation |
@Document("orders")
public record OrderDoc(
@Id String id,
@Indexed Long customerId,
OrderStatus status,
@Field(targetType = FieldType.DECIMAL128) BigDecimal total,
Instant placedAt,
List<LineDoc> lines,
@Version Long version) {
public record LineDoc(String sku, String name, int qty,
@Field(targetType = FieldType.DECIMAL128)
BigDecimal unitPrice) { }
}6Practical Examples
6.1 Money stored as double
An invoicing module stored amounts as BSON doubles. Monthly totals differed from the ledger by a few paise, triggering audit findings. Migrating to Decimal128 (and BigDecimal in Java) fixed rounding; a validator now rejects non-decimal totals.
6.2 Mixed id types
Some services wrote customerId as a string, others as a number. Queries {customerId: 17} silently missed a third of the orders. A validator enforcing bsonType: "long" plus a migration aligned the data.
6.3 Worked example — aggregate boundaries for an order
| Candidate data | Inside the order document? | Reason |
|---|---|---|
| Lines (≤ 200) | Yes | Read/written with the order; bounded |
| Shipping address snapshot | Yes | Must not change when customer edits address |
| Customer profile | No (id + name snapshot) | Independent lifecycle |
| Product catalogue details | Snapshot of name/price only | Order keeps price at purchase time |
| Payment attempts | Separate collection or small embedded array | May grow; separate lifecycle |
6.4 Worked example — inserting and reading with the driver
CodecRegistry registry = CodecRegistries.fromRegistries(
MongoClientSettings.getDefaultCodecRegistry(),
CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()));
MongoCollection<OrderDoc> orders = client.getDatabase("shop")
.getCollection("orders", OrderDoc.class).withCodecRegistry(registry);
orders.insertOne(new OrderDoc(null, 17L, OrderStatus.PAID, new BigDecimal("4500.00"),
Instant.now(), List.of(new OrderDoc.LineDoc("SKU-1", "Nimbus X", 2,
new BigDecimal("2250.00"))), null));
OrderDoc o = orders.find(Filters.eq("customerId", 17L)).first();6.5 Worked example — schema validation rollout
| Step | Setting |
|---|---|
| 1. Observe | validationAction: "warn" — violations logged, writes accepted |
| 2. Fix producers | Correct services writing invalid documents |
| 3. Clean data | Migration for historical violations |
| 4. Enforce | validationAction: "error", validationLevel: "strict" |
| 5. Existing bad docs | validationLevel: "moderate" during transition (only valid docs checked on update) |
6.6 Worked example — polymorphic documents
{ "_id": "blk-1", "type": "text", "markdown": "## Hello" }
{ "_id": "blk-2", "type": "image", "url": "https://…/a.png", "alt": "Diagram" }
{ "_id": "blk-3", "type": "video", "provider": "yt", "videoId": "abc123" }public sealed interface Block permits TextBlock, ImageBlock, VideoBlock { }
@TypeAlias("text") public record TextBlock(String markdown) implements Block { }
@TypeAlias("image") public record ImageBlock(String url, String alt) implements Block { }
@TypeAlias("video")
public record VideoBlock(String provider, String videoId) implements Block { }Spring Data stores a _class/type alias to restore the correct Java type; sealed interfaces keep handling exhaustive.
6.7 Worked example — document size budget
| Part of a product document | Size |
|---|---|
| Core fields | 1.5 KB |
| Attributes (50) | 2 KB |
| Embedded top 10 reviews | 6 KB |
| Image metadata (8) | 1 KB |
| Total | ~10.5 KB |
Rule of thumb: documents read on every request should be KBs, not MBs; large blobs belong in object storage with a URL in the document.
6.8 Worked example — field naming and storage
| Choice | Effect on 50 M documents |
|---|---|
Field names like customerShippingAddressLine1 | Stored per document; ~30 bytes each |
| Compression (snappy/zstd) | Largely offsets repeated names |
Cryptic names (csa1) | Saves little after compression, hurts readability |
6.9 Worked example — time series collection
db.createCollection("readings", {
timeseries: { timeField: "ts", metaField: "sensor", granularity: "seconds" },
expireAfterSeconds: 60 * 60 * 24 * 90
});
db.readings.insertOne({ ts: new Date(),
sensor: { id: "S-42", site: "KOP" }, value: 21.4 });| Benefit | Explanation |
|---|---|
| Automatic bucketing | Many readings stored per internal bucket document |
| Compression | Columnar compression within buckets |
| TTL | Old data expires automatically |
6.10 Worked example — JSONB alternative for the same data
CREATE TABLE orders (
id bigint PRIMARY KEY, customer_id bigint NOT NULL REFERENCES customer,
status text NOT NULL, total numeric(12,2) NOT NULL, placed_at timestamptz NOT NULL,
lines jsonb NOT NULL, metadata jsonb NOT NULL DEFAULT '{}');
CREATE INDEX ON orders USING gin (lines jsonb_path_ops);| Choose JSONB when | Choose a document database when |
|---|---|
| Most data relational; some flexible parts | Most data document-shaped |
| FKs and SQL reporting needed | Horizontal scale and document operators central |
6.11 Worked example — reading documents in a Spring Boot 4 service
public interface OrderDocRepository extends MongoRepository<OrderDoc, String> {
List<OrderDoc> findTop20ByCustomerIdOrderByPlacedAtDesc(Long customerId);
@Query(value = "{ 'status': ?0 }", fields = "{ 'total': 1, 'placedAt': 1 }")
List<OrderSummary> findSummariesByStatus(OrderStatus status);
}Projections via fields return only needed fields — the document equivalent of selecting columns.
6.12 Worked example — collections per tenant or shared?
| Model | Pros | Cons |
|---|---|---|
Shared collection with tenantId field + compound indexes | Simple operations, scales to many tenants | Noisy neighbours; every query must filter |
| Collection per tenant | Isolation, easy per-tenant drop | Thousands of collections → many files/indexes |
| Database per tenant | Stronger isolation, per-tenant backup | Operational overhead |
7Common Problems & Mistakes
- Doubles for money, strings for dates.
- Inconsistent types for the same field.
- Unbounded arrays and oversized documents.
- No validation in shared collections.
- Documents mirroring relational tables (one document per row, many lookups).
- Large binaries inside documents.
8Performance & Production Considerations
| Aspect | Guideline |
|---|---|
| Document size | KBs; bounded arrays |
| Types | Decimal128, Date, consistent ids |
| Validation | $jsonSchema on important collections |
| Compression | zstd for large collections |
| Projections | Return only needed fields |
9Architecture & Design Considerations
- Design documents as aggregates with clear boundaries.
- Treat the schema as a contract (validators, typed classes, versioning).
- Keep large binaries in object storage.
- Compare with JSONB when the domain is mostly relational.
10Interview Questions & Answers
What is a document in a document database?
A document is a self-describing record of field and value pairs, where a value can be a scalar, a nested document or an array, so one document can hold a whole order with its lines and shipping address. Every document has an _id that is unique within its collection and immutable, by default an ObjectId whose leading bytes encode its creation time. Because field names travel with the data, documents in one collection can differ in shape unless a validator restricts them. The key property is atomicity: a write to one document, including its nested arrays, is atomic, which is why documents should be designed around data that is read and written together.
What is the difference between JSON and BSON?
JSON is a human-readable text format with only strings, numbers, booleans, null, objects and arrays. BSON is MongoDB's binary encoding of JSON-like documents. It adds types JSON lacks, notably Date, Decimal128, ObjectId, 32- and 64-bit integers, Binary and UUID, so money, timestamps and identifiers keep exact semantics. It is also built for traversal: documents and strings carry length prefixes and every value has a type byte, so the server can skip fields without parsing them and compare typed values in indexes. The cost is that field names are stored in every document, which compression largely offsets. Extended JSON shows these types in text form, for example $numberDecimal.
What is a collection?
A collection is a named group of documents inside a database, roughly the counterpart of a table, but without a fixed set of columns: each document carries its own fields. Indexes, schema validation rules, TTL expiry and sharding are all defined per collection, so it is also the unit of operational behaviour. MongoDB creates a collection implicitly on first insert, which is convenient but means a typo silently creates a new collection, so production code should create collections explicitly with validators. Specialised forms exist too: capped collections for logs, time series collections for measurements, clustered collections ordered by _id, and read-only views defined by an aggregation pipeline.
How should money be stored in MongoDB?
Store money as BSON Decimal128 and map it to BigDecimal in Java, never as a double. A double is binary floating point, so values like 0.1 cannot be represented exactly, totals drift by paise and ledgers stop reconciling. Decimal128 holds 34 significant decimal digits exactly. In Spring Data MongoDB, annotate the field with @Field(targetType = FieldType.DECIMAL128), because the default BigDecimal mapping has historically been a string, which sorts and compares wrongly. Keep the currency explicit next to the amount, and enforce bsonType decimal in a $jsonSchema validator so a misconfigured producer cannot write doubles. Some teams store integer minor units as a long instead, which also works when applied consistently.
What is the maximum document size and how should you design for it?
A single BSON document can be at most 16 MB, and exceeding it is a hard write error, not a warning. The real target is far smaller: documents read on every request should be kilobytes, because the whole document is loaded into cache, sent over the network and rewritten on update. The usual way to approach the limit is an unbounded array, such as comments, events or audit entries appended forever. Bound arrays, move growing children into their own collection or use the bucket pattern, embed only snapshots or the top few items, and keep binaries in object storage with a URL in the document. GridFS exists, but object storage is usually better.
How do you enforce structure in a flexible-schema database?
A flexible schema means the database will not enforce structure unless you ask, so I enforce it in layers. On important collections a $jsonSchema validator checks required fields, BSON types and enums, rolled out with validationAction warn first and switched to error once producers are fixed. In the application, typed records or classes with explicit converters define the shape every write must have. Each document carries a schemaVersion field so readers can handle old shapes and migrations can upgrade them lazily or in batches. Contract tests and shared schema definitions catch breaking changes between services. Together these keep flexibility for genuine variation while stopping accidental drift, such as ids stored as strings and numbers.
When would you use PostgreSQL JSONB instead of MongoDB?
Choose PostgreSQL JSONB when the domain is mostly relational and only some attributes are genuinely flexible, such as product specifications or partner metadata next to typed order columns. You keep foreign keys, transactions across tables, full SQL joins and reporting, and you avoid running a second database technology. Choose MongoDB when most of the data is document-shaped aggregates and you need native horizontal sharding, rich partial updates of nested arrays with operators such as $push and array filters, and document-oriented queries at scale. A JSONB update rewrites the whole value, so frequent in-place changes to large JSON values favour MongoDB. Team skills and existing operational capability matter as much as features.
What principle guides document boundaries?
Design each document as an aggregate: the data the application reads and writes together, with one lifecycle and one consistency boundary. An order document embeds its bounded list of lines and a snapshot of the shipping address, because they are created and changed with the order. The customer profile and the product catalogue stay in their own collections, referenced by id, with only the few fields that must be frozen at purchase time, such as product name and price, copied in. Unbounded or independently changing data, like payment attempts or reviews, lives elsewhere. Get these boundaries right and most operations become single-document reads and atomic single-document writes, without multi-document transactions or $lookup.
Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.