ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 6 · Databases, APIs & Integration
  4. Volume IV
  5. Document Model
Book 6 · Volume IV — NoSQL, Caching & Polyglot Persistence · Topic 2.1

Document Model

JSON/BSON, documents and collections

9 min readStage 3 · Systems8 interview questions
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. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Storage of Documents
  5. 4A. Deep Dive — Document Model vs PostgreSQL JSONB
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 10. Interview Questions & Answers

1Concept / Definition

The document model stores data as self-describing, hierarchical records — documents — grouped into collections.

Document database hierarchy
Figure 1 — Document database hierarchy
TOC termDefinition
JSON / BSONJSON 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)
DocumentsRecords of field–value pairs where values may be scalars, nested documents or arrays; each has a unique _id
CollectionsNamed groups of documents, analogous to tables but without a fixed column set (optionally validated)
Table 1 — Document model vocabulary

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.

Rows vs documents
Figure 2 — Rows vs documents

3Core Concepts

3.1 JSON/BSON

JSON vs BSON
Figure 3 — JSON vs BSON
Important BSON types and Java mapping
Figure 4 — Important BSON types and Java mapping
PitfallConsequenceCorrect type
Money as doubleRounding errors (0.1 + 0.2)Decimal128 ↔ BigDecimal
Dates as stringsWrong sorting, no range queries by time zoneDate ↔ Instant
Numeric ids as strings sometimes, numbers other timesQueries miss documents ("17" ≠ 17)One consistent type
UUID legacy binary subtypesCross-driver incompatibilityUuidRepresentation.STANDARD
Table 2 — Types matter even in flexible schemas
JSON
{ "_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

Anatomy of a document
Figure 5 — Anatomy of a document
Document ruleDetail
_idRequired, unique per collection, immutable; default ObjectId (sortable by creation time)
Size≤ 16 MB (BSON); design well below (typically < 1 MB, ideally KBs)
Field namesCase-sensitive; $ and . restricted; keep short but meaningful
NestingUp to 100 levels; paths addressed with dot notation (name.first)
ArraysOrdered; indexable (multikey); avoid unbounded growth
AtomicityWrites to one document are atomic, including nested arrays
Table 3 — Documents

3.3 Collections

Collection featureUse
Schema validation ($jsonSchema)Enforce required fields, types, enums
Capped collectionsFixed-size, insertion-ordered (logs)
Time series collectionsOptimised storage for measurements
Clustered collectionsDocuments stored in _id order
TTL indexesAutomatic expiry
ViewsRead-only aggregation-defined collections
Table 4 — Collection types and features
JAVAJAVASCRIPT
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

LayerMongoDB (WiredTiger)
RecordBSON document stored in a B-tree keyed by internal record id (or _id for clustered)
CompressionSnappy (default), zstd or zlib per collection; prefix compression for indexes
ConcurrencyDocument-level optimistic concurrency (write conflicts retried internally)
UpdatesIn-memory updates; checkpoints every 60 s; journal (WAL) for durability
IndexesSeparate B-trees mapping keys → record ids
Table 5 — How documents are stored
BSON encoding detailBenefit
Length prefixes on documents/stringsSkip fields without parsing
Type bytesTyped comparisons and indexes
Field names stored per documentFlexibility — but repeated names cost space (compression helps)
Table 6 — Why BSON rather than raw JSON

4ADeep Dive — Document Model vs PostgreSQL JSONB

AspectMongoDB documentsPostgreSQL JSONB
Primary modelDocuments everywhereRelational with JSON columns
TypesRich BSON typesJSON types (numbers, strings…) + SQL types around
IndexingAny path, compound, multikeyGIN (containment), expression indexes on paths
Partial updates$set, $push, array filtersjsonb_set (rewrites the value; TOAST)
Joins$lookup (limited)Full SQL joins
Scale-outNative shardingPartitioning; Citus for distribution
Best fitDocument-shaped domain at scaleRelational core with flexible attributes
Table 7 — Two ways to store documents
Relational ↔ document terminology
Figure 6 — Relational ↔ document terminology

5APIs / Features / Syntax

APIPurpose
MongoClient, MongoDatabase, MongoCollection<T>Driver entry points
Document, BsonDocumentGeneric document representations
POJO/record codecs (PojoCodecProvider, automatic record support)Typed mapping
Spring Data @Document, @Id, @Field, @Indexed, @VersionAnnotation mapping
MongoCustomConversionsCustom type converters (value objects)
db.createCollection(… validator …), collModValidation
Table 8 — Document APIs
JAVA
@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 dataInside the order document?Reason
Lines (≤ 200)YesRead/written with the order; bounded
Shipping address snapshotYesMust not change when customer edits address
Customer profileNo (id + name snapshot)Independent lifecycle
Product catalogue detailsSnapshot of name/price onlyOrder keeps price at purchase time
Payment attemptsSeparate collection or small embedded arrayMay grow; separate lifecycle
Table 9 — Document = aggregate

6.4 Worked example — inserting and reading with the driver

JAVA
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

StepSetting
1. ObservevalidationAction: "warn" — violations logged, writes accepted
2. Fix producersCorrect services writing invalid documents
3. Clean dataMigration for historical violations
4. EnforcevalidationAction: "error", validationLevel: "strict"
5. Existing bad docsvalidationLevel: "moderate" during transition (only valid docs checked on update)
Table 10 — Introduce validation without breaking production

6.6 Worked example — polymorphic documents

JSON
{ "_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" }
JAVA
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 documentSize
Core fields1.5 KB
Attributes (50)2 KB
Embedded top 10 reviews6 KB
Image metadata (8)1 KB
Total~10.5 KB
Table 11 — Keep documents small enough to read often and update cheaply

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

ChoiceEffect on 50 M documents
Field names like customerShippingAddressLine1Stored per document; ~30 bytes each
Compression (snappy/zstd)Largely offsets repeated names
Cryptic names (csa1)Saves little after compression, hurts readability
Table 12 — Prefer clear names; rely on compression

6.9 Worked example — time series collection

JAVAJAVASCRIPT
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 });
BenefitExplanation
Automatic bucketingMany readings stored per internal bucket document
CompressionColumnar compression within buckets
TTLOld data expires automatically
Table 13 — Specialised collection types extend the document model

6.10 Worked example — JSONB alternative for the same data

SQL
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 whenChoose a document database when
Most data relational; some flexible partsMost data document-shaped
FKs and SQL reporting neededHorizontal scale and document operators central
Table 14 — Same document, different home

6.11 Worked example — reading documents in a Spring Boot 4 service

JAVA
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?

ModelProsCons
Shared collection with tenantId field + compound indexesSimple operations, scales to many tenantsNoisy neighbours; every query must filter
Collection per tenantIsolation, easy per-tenant dropThousands of collections → many files/indexes
Database per tenantStronger isolation, per-tenant backupOperational overhead
Table 15 — Tenancy shapes collection design

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

AspectGuideline
Document sizeKBs; bounded arrays
TypesDecimal128, Date, consistent ids
Validation$jsonSchema on important collections
Compressionzstd for large collections
ProjectionsReturn only needed fields
Table 16 — Operational guidelines

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

Q1L1 · BasicConcept

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.

Q2L1 · BasicInternals

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.

Q3L2 · IntermediateConcept

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.

Q4L2 · IntermediateTricky

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.

Q5L3 · Senior EngineerTricky

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.

Q6L3 · Senior EngineerDesign

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.

Q7L4 · Technical ArchitectTrade-off

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.

Q8L5 · Solution ArchitectDesign

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.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.