intermediate
Documents
Model aggregate-shaped JSON documents where locality, nesting, and update size match the product flow.
A MongoDB document is a BSON record — typically one JSON-shaped aggregate that your application reads or updates as a unit. Good document design starts from access patterns: what fields are fetched together, how often nested arrays grow, and how large a single write becomes.
// Order aggregate: one read serves checkout summary
{
_id: ObjectId("..."),
customerId: "c_12",
status: "paid",
items: [{ sku: "A1", qty: 2, price: 19.99 }],
totals: { subtotal: 39.98, tax: 3.2 },
createdAt: ISODate("2026-06-15T10:00:00Z")
}
| Concern | Document lever | |---------|----------------| | Read locality | Embed related data read together | | Update contention | Split hot fields into separate docs | | Growth | Cap array size; archive or bucket history | | Schema drift | Application validation + optional JSON Schema |
`_id` is immutable; choose natural keys only when stable. Field names and types should stay predictable for indexes and aggregation.
On interviews: explain why you shaped one document instead of many rows, and name the update/read trade-off.
Common pitfalls: unbounded arrays inside a document; mixing unrelated entities because "Mongo is schemaless"; documents that exceed 16 MB; rewriting the whole document for tiny field changes when a subdocument split would help.
The trade-off is between read locality and write amplification — deeper embedding speeds reads but makes concurrent updates and document growth harder to control.
Checklist:
- Name the dominant read and write paths.
- Show one aggregate-shaped document example.
- Explain nesting vs splitting by contention and growth.
- Mention BSON limits and validation ownership.