This is the module that decides whether the project succeeds. Everything else in MongoDB is recoverable; a wrong document model is a migration.
Embed when the data is read together and bounded. An order's lines belong inside the order: they are always read with it, they are written once, and there are tens of them, not millions. One read returns everything, atomically, with no join.
Reference when the data is large, unbounded, or shared. A customer's orders do not belong inside the customer document: there may be thousands, they grow forever, and they are queried independently. The limit is concrete - a BSON document may not exceed 16 MB - and an unbounded array is a document that will eventually hit it and stop accepting writes.
The decision rules, in order:
- What reads this, and how often? Design for the dominant access pattern.
- Is the embedded side bounded? If it grows without limit, reference.
- Is it updated independently? Updating one embedded element rewrites the containing document.
- Is it shared? Duplicated data must be updated everywhere, so embed a copy only when you can tolerate it being stale, and then say so.
The extended reference pattern is the usual compromise: store the reference and the two or three fields you always display. An order line keeps productId plus name and price as sold, which is correct for an invoice anyway, since the current price is not the price charged.
"Schemaless" is misleading. MongoDB will not enforce a shape unless you ask; your application still has one. JSON Schema validators write it down in the database: required fields, types, ranges, enumerated values, and nested object rules. Use validationLevel: "strict" for new collections and "moderate" when adding one to a collection that already holds documents that would fail. Without a validator, schema drift is not detected - it is discovered.
The aggregation pipeline is MongoDB's real query language. Stages flow into one another: $match (filter - always put it first), $project, $group, $sort, $unwind (one document per array element), $lookup (a left outer join), $facet (several independent pipelines over the same input, which is how faceted search is built) and $merge/$out (write the result to a collection, which is how you build a materialised rollup).
Laboratory exercise 2 - two models, measured.
Design two schemas for the capstone's product catalogue and order system. The contrast is the point: one heavily embedded (products with variants and reviews inside; orders with lines, payment and shipping inside), and one normalised with references and $lookup.
Implement both with JSON Schema validators. Test every validator by attempting to insert a document that violates it.
Write the representative queries against both: faceted catalogue search (by category, price band and brand, with counts), a product page with its variants and recent reviews, place an order, read an order complete, and a monthly revenue report by category.
Measure both models on the faceted search and the product page: documents examined, index use, and execution time from explain("executionStats").
Then demonstrate the 16 MB ceiling: write a script that appends reviews to an embedded array until the document is rejected, and record how many it took.
Deliverable: both schemas with validators, every validator's rejection output, all queries in both models, the explain-based comparison, the 16 MB demonstration, and a page arguing for one model on the access patterns.
// ------------------------------------------------------------------
// EMBED: read together, bounded, written as a unit.
// ------------------------------------------------------------------
db.orders.insertOne({
_id: ObjectId(),
customerId: ObjectId("655f.."), // reference: unbounded side
status: "pending",
placedAt: new Date(),
// Embedded: always read with the order, bounded (tens), written once.
lines: [
{ productId: ObjectId("655a.."),
// EXTENDED REFERENCE: the reference PLUS the fields always shown.
// name and price AS SOLD - which is correct for an invoice
// anyway, because today's price is not the price charged.
name: "Mechanical keyboard", sku: "KB-001",
unitPrice: NumberDecimal("89.99"), quantity: 1 }
],
// Embedded: one-to-one, always read with the order.
shipping: { line1: "1 High St", city: "London", postcode: "E1 1AA" },
total: NumberDecimal("89.99")
});
// ------------------------------------------------------------------
// REFERENCE: large, unbounded, or queried independently.
// ------------------------------------------------------------------
// Reviews do NOT go inside the product. A popular product gets
// 100,000 of them, and a BSON document may not exceed 16 MB - so an
// unbounded array is a document that will one day stop accepting
// writes. Demonstrate this in the lab; it is more memorable than
// reading it.
db.review.insertOne({
productId: ObjectId("655a.."),
rating: 5, body: "...", createdAt: new Date()
});
// The product keeps a bounded SUMMARY, maintained on write:
db.product.updateOne({_id: ObjectId("655a..")}, {
$inc: {"reviewSummary.count": 1, "reviewSummary.ratingSum": 5},
// A bounded array: $slice caps it, so the document cannot grow
// without limit. This is the pattern for "most recent N".
$push: {recentReviews: {$each: [{rating: 5, body: "..."}], $slice: -5}}
});
// ------------------------------------------------------------------
// "Schemaless" is misleading. Write the schema DOWN.
// ------------------------------------------------------------------
db.createCollection("product", {
validator: { $jsonSchema: {
bsonType: "object",
required: ["sku", "name", "price", "category", "active"],
additionalProperties: false, // catches typos in field names,
// which is most of schema drift
properties: {
_id: { bsonType: "objectId" },
sku: { bsonType: "string", pattern: "^[A-Z]{2}-[0-9]{3,6}$" },
name: { bsonType: "string", minLength: 1, maxLength: 200 },
price: { bsonType: "decimal", description: "Decimal128, not double" },
category: { enum: ["keyboards","mice","monitors","audio"] },
active: { bsonType: "bool" },
variants: { bsonType: "array", maxItems: 50, items: {
bsonType: "object", required: ["sku","stock"],
properties: { sku: {bsonType:"string"}, stock: {bsonType:"int", minimum: 0} }
}},
reviewSummary: { bsonType: "object", properties: {
count: {bsonType:"int", minimum: 0}, ratingSum: {bsonType:"int", minimum: 0}
}}
}
}},
validationLevel: "strict", // "moderate" when adding a validator
validationAction: "error" // to a collection whose existing
}); // documents would fail
// TEST IT. Every validator, with the rejection recorded:
db.product.insertOne({sku: "bad", name: "x", price: 9.99,
category: "keyboards", active: true});
// -> Document failed validation
// sku does not match the pattern; price is a double, not a decimal
db.runCommand({collMod: "product", validator: {...}, validationLevel: "moderate"});
// ------------------------------------------------------------------
// AGGREGATION: MongoDB's real query language.
// ------------------------------------------------------------------
// $match FIRST, always. It is the only stage that can use an index,
// and a $match after a $group has nothing left to filter cheaply.
db.orders.aggregate([
{ $match: { placedAt: {$gte: ISODate("2026-01-01")}, status: "paid" } },
{ $unwind: "$lines" }, // one doc per line
{ $group: {
_id: { month: {$dateTrunc: {date: "$placedAt", unit: "month"}},
product: "$lines.productId" },
revenue: { $sum: {$multiply: ["$lines.unitPrice", "$lines.quantity"]} },
units: { $sum: "$lines.quantity" } } },
{ $sort: { "_id.month": 1, revenue: -1 } },
{ $lookup: { // left outer join
from: "product", localField: "_id.product",
foreignField: "_id", as: "product",
pipeline: [{ $project: { name: 1, category: 1 } }] } },
{ $unwind: { path: "$product", preserveNullAndEmptyArrays: true } },
{ $merge: { into: "monthly_revenue", // materialise it
on: "_id", whenMatched: "replace" } }
]);
// $lookup is a join and it is NOT free - it runs per input document.
// If you find yourself using it on the hot path, that is usually the
// model telling you to embed.
// ------------------------------------------------------------------
// $facet: how faceted search is actually built. Several independent
// pipelines over ONE pass of the input.
// ------------------------------------------------------------------
db.product.aggregate([
{ $match: { active: true, $text: {$search: "mechanical"} } },
{ $facet: {
results: [ {$sort: {price: 1}}, {$skip: 0}, {$limit: 20},
{$project: {name:1, price:1, category:1}} ],
byCategory: [ {$group: {_id: "$category", n: {$sum: 1}}},
{$sort: {n: -1}} ],
byPriceBand: [ {$bucket: {
groupBy: "$price",
boundaries: [NumberDecimal("0"), NumberDecimal("50"),
NumberDecimal("150"), NumberDecimal("500")],
default: "500+", output: {n: {$sum: 1}} }} ],
total: [ {$count: "n"} ]
}}
]);
// One query returns the page, every facet with its counts, and the
// total. In SQL this is four round trips or a very large UNION.
// ------------------------------------------------------------------
// Measure the models. This is the deliverable.
// ------------------------------------------------------------------
db.product.find({category: "keyboards", price: {$lt: NumberDecimal("100")}})
.explain("executionStats").executionStats;
// nReturned : 42
// totalDocsExamined : 42 <- equal to nReturned: ideal
// totalKeysExamined : 42
// executionTimeMillis : 2
//
// totalDocsExamined >> nReturned means the index is not selective, or
// there is none. Compare this number between your two models; it
// explains the latency better than the time does.
Open this example in the editor and change it. Nothing you type is saved.
Discussion
No questions on this topic yet. Sign in to ask the first one.