Document databases: embed or reference
A document databaseDocument databaseA database that stores each record as a JSON-like document with nested objects and arrays.Open in glossary → stores each record as a document: a JSON-like object that can contain nested objects and lists. MongoDB is the best known; Firestore and Couchbase are others. Documents with the same purpose live in a collection, the rough equivalent of a table, but nothing forces them to have the same fields.
An order in a relational database is spread over orders and order_items, joined when you need them. In MongoDB, the order page can be one document:
{
_id: 1001,
customerId: 42,
status: "PAID",
items: [
{ productId: 7, name: "Mug", quantity: 2, unitPrice: 9.50 },
{ productId: 3, name: "Coffee beans 1 kg", quantity: 1, unitPrice: 24.00 }
],
total: 43.00
}Reading the order is one lookup, with no join. That’s the main idea: store data the way the app reads it.
The big design question is embed or reference:
- Embed (put it inside the document) when the data is read together with the parent, belongs only to it, and stays small. Order items are the classic example.
- Reference (store just an id, like
customerId: 42) when the data is shared by many documents, changes on its own, or keeps growing. A customer has many orders and can change their email; copying the whole customer into every order would mean updating hundreds of documents.
Queries are written as documents too. db.orders.find({ status: "PAID" }) finds paid orders, and a query on a field inside an array, like { "items.productId": 7 }, finds orders that contain product 7. When a field holds an array, a condition on that field matches if any element matches.
- Embed vs reference: embed what’s read together, owned by the parent and bounded; reference what’s shared, large, unbounded or updated independently. A document is limited to 16 MB (BSON), and every read and write moves the whole document, so growth matters long before the limit.
- Modeling patterns: subset (embed the latest 10 reviews, keep the rest in their own collection), extended reference (copy the fields you display, like
{ customerId, name }, and accept they may be stale), bucket (one document per sensor per hour instead of per reading), computed (maintain counters on write). - Indexes: B-tree like SQL. Compound index order follows ESR: equality fields first, then sort fields, then range fields. An index on an array field is multikey (one entry per element); in a compound multikey index, at most one of the indexed fields can be an array in any one document. Partial, TTL and wildcard indexes exist.
- Joins:
$lookupin the aggregation pipeline does a left outer join, but if most queries need several, the model is fighting the access patterns. - Atomicity: a write to one document is atomic, including its nested arrays, which is why embedding often replaces a transaction. Multi-document transactions exist (replica sets since 4.0, sharded clusters since 4.2), with a 60-second default lifetime and a real cost; design so they’re rare.
- Durability and reads: write concern
majority(the default since 5.0) waits until most replicas have the write; read concern and read preference decide whether a read can see data that a failover may still roll back, or stale data from a secondary. - “Schemaless” means the schema lives in application code.
$jsonSchemavalidators enforce shape on the server; old documents with old shapes stay until you migrate them.
Predict the output
Three products: A has tags ['coffee', 'sale'], B has tags ['coffee'], C has tags ['tea']. How many documents does each query return?
db.products.find({ tags: "coffee" }).count();
db.products.find({ tags: ["coffee"] }).count();A condition on an array field matches when any element matches, so tags: 'coffee' finds A and B. Comparing with an array literal means the whole array must be equal, in the same order: only B has exactly ['coffee']. To require several tags in any order, use $all: tags: { $all: ['coffee', 'sale'] }.
db.orders.insertOne({
_id: 1001,
customerId: 42, // reference: customers live on their own
status: "PAID",
createdAt: ISODate("2026-11-08T10:15:00Z"),
shipping: { name: "Ana Petrović", city: "Novi Sad" }, // embedded snapshot, kept as it was
items: [
{ productId: 7, name: "Mug", quantity: 2, unitPrice: NumberDecimal("9.50") },
{ productId: 3, name: "Coffee beans 1 kg", quantity: 1, unitPrice: NumberDecimal("24.00") }
],
total: NumberDecimal("43.00")
});
// a customer's latest orders: equality on customerId, then the sort
db.orders.createIndex({ customerId: 1, createdAt: -1 });
db.orders.find({ customerId: 42 }).sort({ createdAt: -1 }).limit(20);
// orders that contain product 7: a multikey index on the array
db.orders.createIndex({ "items.productId": 1 });
db.orders.find({ "items.productId": 7 });
// revenue per product, like GROUP BY
db.orders.aggregate([
{ $match: { status: "PAID" } },
{ $unwind: "$items" },
{ $group: { _id: "$items.productId",
revenue: { $sum: { $multiply: ["$items.quantity", "$items.unitPrice"] } } } },
{ $sort: { revenue: -1 } }
]);The blog post that stopped saving
Tap the line with the bug.
// posts: { _id, title, body, authorId, comments: [ ... ] }
function addComment(postId, comment) {
return db.posts.updateOne(
{ _id: postId },
{ $push: { comments: comment } }
);
}
function showPost(postId) {
return db.posts.findOne({ _id: postId });
}Hint: Comments keep coming. What happens to the post document after a popular post gets 80,000 of them?
Every comment makes the post document bigger, forever. This is an unbounded array. With a few comments it works perfectly, which is why it gets shipped. Then a post goes viral: each page view loads all 80,000 comments to show the first 20, every new comment rewrites a multi-megabyte document, and at 16 MB MongoDB refuses the update. Comments simply stop saving on the most popular post.
Comments are many, keep growing and are read in pages, so they get their own collection with a reference to the post. Keep a small subset embedded if the post page shows a preview:
db.comments.createIndex({ postId: 1, createdAt: -1 });
function addComment(postId, comment) {
db.comments.insertOne({ ...comment, postId, createdAt: new Date() });
// optional: keep the 3 newest in the post for the preview
return db.posts.updateOne(
{ _id: postId },
{ $push: { latestComments: { $each: [comment], $position: 0, $slice: 3 } },
$inc: { commentCount: 1 } }
);
}
function commentsPage(postId, before) {
return db.comments.find({ postId, createdAt: { $lt: before } })
.sort({ createdAt: -1 }).limit(20).toArray();
}$slice: 3 trims the array on every push, so latestComments can never grow past three.
Deep diveMongoDB or PostgreSQL with jsonb?Interview favorite
“Our data is JSON, so we should use MongoDB” is the claim to examine. PostgreSQL’s jsonb stores documents in a column, indexes them (GIN for containment, expression indexes for specific fields), and keeps joins, constraints and multi-row transactions around them. Many teams store the stable fields as columns and the variable ones (product attributes, integration payloads) as jsonb.
Where jsonb is weaker:
- Updates replace the whole value: changing one field in a 200 KB document writes a new 200 KB version, plus WAL. MongoDB also rewrites the document on disk, but replication sends only the changed fields.
- Planner estimates: PostgreSQL keeps no statistics inside
jsonbby default, so a filter likeattrs->>'color' = 'red'gets a fixed guess. Expression indexes andCREATE STATISTICSon expressions (PostgreSQL 14+) fix specific cases. - Horizontal scale: MongoDB has built-in sharding and automatic failover in every replica set. PostgreSQL needs extensions or a managed service (Citus, distributed SQL) to shard.
Where MongoDB is weaker: joins and reports across collections, constraints between documents, and transactions that are rare by design. A good answer picks per data shape: varied, self-contained documents read by id at large scale favour MongoDB; related entities with reporting needs favour PostgreSQL with some jsonb. Then name what you’d lose either way.
- Embed what’s read together, owned and bounded; reference what’s shared, unbounded or independently updated. 16 MB document limit; unbounded arrays are the classic bug.
- Patterns: subset, extended reference, bucket, computed. ESR order for compound indexes; at most one array field per document in a compound multikey index.
- One-document writes are atomic; multi-document transactions exist but are costly.
majoritywrite concern by default since 5.0. jsonbin PostgreSQL covers many document needs; weaker on large partial updates, statistics and built-in sharding.
db.orders.createIndex({ customerId: 1, createdAt: -1 }); // equality, then sort
db.orders.find({ customerId: 42 }).sort({ createdAt: -1 }).limit(20);
db.posts.updateOne({ _id: id }, { $push: { latest: { $each: [c], $position: 0, $slice: 3 } } });
db.products.find({ tags: { $all: ["coffee", "sale"] } });Check this part
Order items are shown with the order and belong only to it. Embed or reference?
Why is pushing every comment into the post document a problem?
Query: equality on status, sort by createdAt, range on total. Which compound index order fits MongoDB's ESR rule?
What is atomic in MongoDB without a transaction?