Embed related data in MongoDB when it is small, bounded, and almost always read together with its parent (one-to-one or one-to-few). Reference it when the relationship is one-to-many with high or unbounded cardinality, or the related entity is large or shared across many parents. The hard ceiling that forces a reference is the 16 MB BSON document limit.
Every MongoDB schema decision comes down to one fork: do you embed the related data as a subdocument or array inside one document, or do you reference it by storing its _id (or another key) and reading the related document separately? Embedding gives you a single-document read that is fast and atomic. Referencing keeps documents small and avoids duplicating data that lives in many places, at the cost of a second query or a $lookup join. Below is the decision table, the same relationship modeled both ways, a $lookup example, the established patterns that sit between the two extremes, and the two field types people most often get wrong in those documents: money (Decimal128 or integer cents, never a double) and UUIDs (BSON Binary subtype 4, not a string).
The detail that decides it: reference when the related entity changes on its own and you do not want to duplicate it, and remember that an unbounded embedded array eventually blows past the 16 MB BSON document limit.
Embed or reference: the core decision
MongoDB stores data as BSON documents, and a document can nest other documents and arrays to any depth you like. That nesting is the whole point of the document model, so the first instinct should be to embed. The MongoDB manual puts it plainly: data that is accessed together should be stored together, and you model for your application's query patterns, not for a normalized textbook schema.
This is the opposite instinct from relational design, and it is worth saying out loud. In SQL you normalize first (split everything into its own table, join on read) and denormalize only when the joins hurt. In MongoDB you start denormalized (embed the related data in the document that reads it) and reach for references only when embedding stops paying off. If you carry relational habits into MongoDB you end up with a pile of tiny collections and a $lookup on every query, which is the slow path the document model was built to avoid.
Two mechanisms, two trade-offs:
- Embedding nests the related data inside the parent document. One read returns everything. A single-document write is atomic in MongoDB, so updating the parent and its embedded children together is all-or-nothing with no transaction needed.
- Referencing stores a pointer (
_id, slug, or any key) and leaves the related data in its own collection. You resolve it with a second query or an aggregation$lookup. Documents stay small, shared data lives in one place, but you give up the single-read and the free atomicity, and MongoDB enforces no foreign keys, so referential integrity is your application's job.
When to embed
Embed when all of these hold, and the more that hold the stronger the case:
- The related data is read together with the parent almost every time.
- The relationship is one-to-one or one-to-few (a handful, not thousands).
- The embedded data is bounded in size and does not grow without limit.
- You do not need to query or update the child independently of the parent.
A user with one address, an order with its line items, a blog post with its tags: these are textbook embeds. You fetch the order, you get the line items in the same read, and you update them atomically.
A useful gut-check for the array size is the "rule of thousands": if the embedded array stays in the dozens or low hundreds and has a real upper bound, embedding is safe. Once it can run into the thousands with no ceiling, treat it as unbounded and reference (or bucket) it instead. The number is a heuristic, not a hard threshold; the document and array size, not the element count alone, is what actually matters.
// Order with embedded line items: one read, atomic writes
{
_id: ObjectId("6512a1f0c3b9a2e4d8f10001"),
customerId: ObjectId("6512a1f0c3b9a2e4d8f10999"),
status: "shipped",
placedAt: ISODate("2026-05-28T14:02:00Z"),
items: [
{ sku: "TE-MUG-01", name: "Field Notes Mug", qty: 2, unitPrice: 1400 },
{ sku: "TE-CAP-03", name: "Logo Cap", qty: 1, unitPrice: 2200 }
],
shippingAddress: {
line1: "12 Bayswater Rd", city: "Colombo", postcode: "00300", country: "LK"
}
}
The line items have no meaning outside this order and the address is a single subdocument, so both belong inside the parent.
When to reference
Reference when embedding would force you to duplicate data, grow a document without bound, or drag along data you rarely need:
- The relationship is one-to-many or many-to-many with high or unbounded cardinality.
- The related entity is large, or shared across many parents (the same author on a thousand posts).
- The related entity changes on its own and you do not want to update copies scattered across documents.
A blog post referencing an author is the canonical case. The author is one record shared by every post they wrote; if you embedded the full author object into each post, a name change means rewriting every post.
When you reference a one-to-many relationship, put the link on the many side: each post carries the authorId, each comment carries a postId. The parent stays small and fixed in size no matter how many children it gains, and you index the child collection on the parent key for fast lookups. An array of child _ids on the parent only works when that array is genuinely bounded, otherwise you have reinvented the unbounded-array problem the reference was meant to dodge.
// Post references its author by _id; author lives once in its own collection
{
_id: ObjectId("6512a1f0c3b9a2e4d8f20001"),
title: "MongoDB Schema Design: Embedding vs Referencing",
slug: "mongodb-embed-vs-reference-schema",
authorId: ObjectId("6512a1f0c3b9a2e4d8f30007"),
body: "Every MongoDB schema decision comes down to one fork...",
publishedAt: ISODate("2019-11-19T09:00:00Z")
}
// authors collection
{
_id: ObjectId("6512a1f0c3b9a2e4d8f30007"),
name: "Ishan Karunaratne",
bio: "Tech architect, 20+ years shipping real systems.",
twitter: "@techearl"
}The 16 MB limit is the hard line
The constraint that turns "should I embed?" into "I cannot embed" is the 16 MB maximum BSON document size. Every document, with all its embedded subdocuments and arrays, has to fit under that ceiling. An unbounded embedded array (comments on a viral post, events on a busy device, "massive arrays" in MongoDB's own anti-pattern language) will eventually hit it.
Long before you reach 16 MB the performance cost shows up. A large document is more expensive to read, ship over the wire, and hold in the working set, and growing an array means MongoDB rewrites the whole document. So the rule for any unbounded one-to-many is: do not embed the many side without a cap. Reference it, or use one of the patterns below (subset, bucket) that embeds a bounded slice and references the rest.
Joining referenced data with $lookup
When you reference, you eventually need the related data back. The aggregation $lookup stage performs a left outer join from one collection into another:
// Join each post to its author document
db.posts.aggregate([
{ $match: { slug: "mongodb-embed-vs-reference-schema" } },
{
$lookup: {
from: "authors",
localField: "authorId",
foreignField: "_id",
as: "author"
}
},
{ $unwind: "$author" }, // turn the 1-element array into a subdocument
{ $project: { title: 1, "author.name": 1, "author.bio": 1 } }
])$lookup writes the matched documents into an array field (author here), which is why a single-match join is usually followed by $unwind to flatten it. Two things to keep in mind: a $lookup is less efficient than an embedded read (it is a join, with all the work a join implies), and there is no enforced referential integrity, so a dangling authorId that points at a deleted author just returns an empty array. The application has to keep references honest.
Embed vs reference decision table
| Factor | Lean embed | Lean reference |
|---|---|---|
| Relationship cardinality | One-to-one, one-to-few | One-to-many, many-to-many, unbounded |
| Access pattern | Parent and child read together | Child queried or used on its own |
| Data size / growth | Small, bounded | Large, or grows without limit |
| Update frequency | Child changes with the parent | Child changes independently |
| Atomicity | Need a single atomic write | Per-collection writes are fine |
| Shared across parents | No, owned by one parent | Yes, one entity many parents |
| Query cost | Single-document read (fast) | Extra query or $lookup join |
No single row decides it. Weigh them together: a one-to-few relationship that is read together and updated together is an obvious embed even if the child could in theory be queried alone.
The same relationship, both ways
Take a blog post and its comments. Embedded, the comments live in the post and one read renders the whole page:
// Embedded: fine while comment count stays bounded
{
_id: ObjectId("6512a1f0c3b9a2e4d8f20001"),
title: "MongoDB Schema Design: Embedding vs Referencing",
body: "Every MongoDB schema decision...",
comments: [
{ author: "dev_anna", text: "Saved me a refactor, thanks.", at: ISODate("2026-05-28T10:00:00Z") },
{ author: "kp_ops", text: "The 16 MB note is the key bit.", at: ISODate("2026-05-28T11:30:00Z") }
]
}That is the right model for a post that gets a few dozen comments. It is the wrong model for a post that might get fifty thousand, because the array is unbounded and marches toward the 16 MB wall. There, reference the comments into their own collection:
// Referenced: comments scale independently, queried and paged on their own
// posts
{ _id: ObjectId("6512a1f0c3b9a2e4d8f20001"), title: "MongoDB Schema Design: Embedding vs Referencing" }
// comments (one document per comment, indexed on postId)
{ _id: ObjectId("..."), postId: ObjectId("6512a1f0c3b9a2e4d8f20001"), author: "dev_anna", text: "Saved me a refactor, thanks.", at: ISODate("2026-05-28T10:00:00Z") }
{ _id: ObjectId("..."), postId: ObjectId("6512a1f0c3b9a2e4d8f20001"), author: "kp_ops", text: "The 16 MB note is the key bit.", at: ISODate("2026-05-28T11:30:00Z") }Now comments page and sort on their own, and the post document stays tiny. The cost is the second query (or a $lookup) to pull comments when you render the page. Same relationship, two schemas, and the deciding factor is purely whether the comment count is bounded.
The patterns between the extremes
Embed-or-reference is not binary. A set of named patterns, popularized in MongoDB's own schema-design material, covers the common middle ground:
- One-to-few: embed. A person's few addresses, a product's handful of variants. Just nest the array.
- One-to-many: reference (or subset). Reference the many side into its own collection. If you almost always need only the most recent few, use the subset pattern: embed the hot slice (last 5 comments, top 3 reviews) in the parent and reference the full set elsewhere.
- One-to-squillions: reference, often with the bucket pattern. For unbounded high-volume data like IoT readings or log lines, store one document per bucket of events (an hour of readings, say) rather than one per event, and reference the device. This keeps the document and index counts sane.
- Extended reference: duplicate a few hot fields. When a join just to grab a name and avatar is wasteful, copy those one or two fields onto the referencing document alongside the
_id. You accept a little duplication to skip the$lookup, and you update the copies when the source changes. - Computed pattern: store the rolled-up result. When reads recompute the same aggregate constantly (a running total, an average rating), compute it on write and store it, rather than recomputing on every read.
These are not exotic. Most production schemas are a mix: embed the one-to-few, reference the one-to-many, extended-reference the hot fields, and bucket the firehose.
Store money in MongoDB
Whether a priced line item is embedded in an order or referenced from a product collection, the amount itself needs an exact type, never a BSON double. The default is Decimal128, a 128-bit IEEE 754 decimal floating-point type with 34 significant decimal digits, created in mongosh with NumberDecimal("9.99"). The high-volume alternative is the integer count of minor units (cents) in a 64-bit NumberLong. Either way, the currency code goes in its own field.
Why a double drifts
A bare literal like 9.99 in mongosh, Node.js, or a JSON document is a BSON double: 64-bit binary floating point. Most decimal fractions have no exact binary representation, so 0.1 + 0.2 lands a hair above 0.3. In a money field that surfaces as 19.99 stored as 19.989999999999998, an aggregation total over ten thousand invoices that is off by a few cents, and an exact-match query like { price: 19.99 } that finds nothing. MongoDB's own monetary-data guide says the same thing: use the decimal type or scale factors, not a double.

Decimal128 with NumberDecimal
Decimal128 was added in MongoDB 3.4 (released November 2016), so any supported server has it:
db.products.insertOne({
name: "Widget",
price: NumberDecimal("9.99"),
currency: "USD"
})
In Extended JSON it serializes as { "$numberDecimal": "9.99" }. Server-side arithmetic stays exact: $sum, $multiply, $add, $inc and $mul all operate on Decimal128 without converting to binary.
Always pass a string. NumberDecimal(9.99) looks identical to NumberDecimal("9.99") but is not: the 9.99 is parsed as a JavaScript double first, so it has already drifted before the constructor sees it, and the resulting decimal preserves the error. The same rule holds in every driver: build the decimal from a string or an exact decimal type, never from a float.
Integer cents in a NumberLong
MongoDB calls this the scale factor method: $19.99 is stored as the integer 1999 and divided by 100 for display. Use NumberLong (BSON int64) so it never degrades into a double:
db.orders_minor.insertMany([
{ orderId: 1, item: "Widget", amountMinor: NumberLong(1999), currency: "USD" },
{ orderId: 1, item: "Setup", amountMinor: NumberLong(500), currency: "USD" },
{ orderId: 1, item: "Fee A", amountMinor: NumberLong(10), currency: "USD" },
{ orderId: 1, item: "Fee B", amountMinor: NumberLong(20), currency: "USD" }
])
db.orders_minor.aggregate([
{ $match: { orderId: 1 } },
{ $group: { _id: "$currency", totalMinor: { $sum: "$amountMinor" } } }
])
// => { "_id": "USD", "totalMinor": NumberLong(2529) } // 2529 cents = $25.29The trade is that the application carries the scale (2 for dollars and euros, 0 for yen) and must apply it consistently. I reach for integer cents on a high-throughput payments or accounting ledger with a team disciplined about the scale convention; for a normal application Decimal128 is less error-prone because the decimal lives in the value, not in everyone's head.
| Approach | Exact? | Precision | Storage | Use when |
|---|---|---|---|---|
BSON double | No, binary drift | ~15-17 binary digits | 8 bytes | Never for money |
Decimal128 (NumberDecimal) | Yes, decimal | 34 decimal digits | 16 bytes | General default, FX and sub-cent included |
Integer cents (NumberLong) | Yes, integer math | full int64 range | 8 bytes | High-volume ledgers, integer arithmetic end to end |
Currency field, validation and an exact total
Store the currency as the three-letter ISO 4217 code in a plain string ("USD", "EUR", "JPY"). 1000 could be dollars or yen, and grouping by currency stops you from summing dollars into euros. A $jsonSchema validator makes the database refuse a stray double:
db.createCollection("orders", {
validator: {
$jsonSchema: {
bsonType: "object",
required: ["price", "currency"],
properties: {
price: { bsonType: "decimal" },
currency: { bsonType: "string", pattern: "^[A-Z]{3}$" }
}
}
}
})For integer cents the same validator uses bsonType: "long" on amountMinor. With Decimal128 line items, an order total stays exact through the pipeline:
db.orders.insertMany([
{ orderId: 1, item: "Widget", price: NumberDecimal("19.99"), currency: "USD" },
{ orderId: 1, item: "Setup", price: NumberDecimal("5.00"), currency: "USD" },
{ orderId: 1, item: "Fee A", price: NumberDecimal("0.10"), currency: "USD" },
{ orderId: 1, item: "Fee B", price: NumberDecimal("0.20"), currency: "USD" }
])
db.orders.aggregate([
{ $match: { orderId: 1 } },
{ $group: { _id: "$currency", total: { $sum: "$price" } } }
])
// => { "_id": "USD", "total": NumberDecimal("25.29") }For a derived amount with sub-cent digits (a tax line, a split), round with { $round: ["$amount", 2] }, which keeps the Decimal128 type and rounds half to even (so 0.125 becomes 0.12). Then keep doubles out of the application too: in Node.js build values with the driver's Decimal128.fromString("9.99") (from the bson package), not new Decimal128(9.99); in Python construct bson.decimal128.Decimal128 from a decimal.Decimal built from the string form; in Java use the driver's Decimal128 / BigDecimal end to end. The relational equivalent is DECIMAL(19,4) or BIGINT cents in MySQL and numeric in Postgres.
Store a UUID in MongoDB
When you reference instead of embed, the key you store is often a UUID. Store it as a BSON Binary value of subtype 4, the standard UUID subtype, not as a 36-character string. In mongosh the UUID("...") helper produces exactly that. MongoDB has no dedicated UUID field type, so the question is only how to represent the 128 bits: as a BSON value the 36-character string costs 41 bytes (a 4-byte length prefix, the 36 bytes, and a null terminator) against 21 bytes for the binary (a 4-byte length prefix, a 1-byte subtype tag, and the 16 raw bytes).
// generate a fresh v4 UUID (mongosh)
UUID()
// UUID("dee11d4e-63c6-4d90-983c-5c9f1e79e96c")
// parse an existing string into the same subtype-4 Binary
UUID("3b241101-e2bb-4255-8caf-4136c566a962")
| Representation | Size | Indexes / sorts on | Time-ordered? | When to use |
|---|---|---|---|---|
| String UUID (36 chars) | 36 bytes (41 as a BSON value) | the hex text, byte by byte | No | Almost never; only quick ad-hoc data |
Binary subtype 4 (UUID) | 16 bytes | the raw 16 bytes | Only if you store a v7 | Any UUID you keep; client-generated ids |
ObjectId | 12 bytes | timestamp-leading bytes | Roughly (4-byte timestamp prefix) | The default _id; server-side ids |
Insert and query a UUID field
db.sessions.insertOne({
_id: new ObjectId(),
token: UUID("3b241101-e2bb-4255-8caf-4136c566a962"),
userId: 42,
createdAt: new Date()
})
// query by the UUID: pass a UUID(), not the raw string
db.sessions.findOne({ token: UUID("3b241101-e2bb-4255-8caf-4136c566a962") })
db.sessions.createIndex({ token: 1 })BSON equality is type-aware, so a findOne with a plain string never matches a subtype-4 Binary. Wrap the value in UUID(...) (or the driver's UUID type) on the way in and on the way out. In the Node.js driver that is new UUID("...") imported from mongodb; in PyMongo it is uuid.UUID with the standard representation; in Java, java.util.UUID. The bytes on disk are identical.
Subtype 3 vs subtype 4
Older systems stored UUIDs as subtype 3, which never standardized byte order: per the MongoDB driver specification, the C# legacy representation reversed bytes within three sub-groups, the Java legacy representation reversed the two 8-byte halves, and the Python legacy representation kept native order. A UUID written by a Java app came back scrambled in a C# app. Subtype 4 fixes the byte order for every driver using the standard representation. Set the representation explicitly in drivers rather than trusting a default that may still be a legacy mode; in PyMongo, STANDARD encodes uuid.UUID to subtype 4, and PYTHON_LEGACY / CSHARP_LEGACY / JAVA_LEGACY exist only to read old data. To migrate, read each value with the legacy representation that wrote it and re-insert it as subtype 4.
ObjectId vs UUID for _id
The default _id is a 12-byte ObjectId: a 4-byte timestamp, a 5-byte per-process random value, and a 3-byte counter. The leading timestamp makes ObjectIds roughly time-ordered (not perfectly monotonic: one-second resolution, client clocks differ), so inserts append to the right-hand side of the _id index. Reach for a UUID _id only when you need a client-generated id before the insert, a globally unique id other systems already speak, or to avoid leaking ObjectId's creation time. Then store it as subtype 4 and set it explicitly:
const id = UUID()
db.accounts.insertOne({ _id: id, email: "ada@example.com", createdAt: new Date() })A random v4 UUID scatters inserts across the _id index, with more page churn and a colder cache. A version 7 UUID leads with a Unix-millisecond timestamp, so stored as subtype 4 it sorts in creation order and regains most of ObjectId's insert locality. Generate a v7 in the application for a write-heavy collection with a UUID _id; otherwise ObjectId is still the honest default. The relational versions of this trade-off are BINARY(16) versus CHAR(36) in MySQL and the native uuid type in PostgreSQL.
What to do next
- For picking an identifier type when you reference (
ObjectIdvsUUID), the trade-offs in store a UUID in MongoDB above are worth a read before you commit to a key. - For modeling currency on an embedded line item or a referenced product, storing money in MongoDB (integer minor units or Decimal128, not floats) avoids a class of rounding bugs.
FAQ
Embed when the related data is small, bounded, and almost always read together with its parent (one-to-one or one-to-few). Reference when the relationship is one-to-many or many-to-many with high cardinality, the related entity is large or shared across many parents, or it changes independently and you do not want duplicate copies.
The guiding rule from MongoDB's data-modeling docs: data accessed together should be stored together, and you model for your application's query patterns, not for normalization.
A single BSON document cannot exceed 16 MB, including every embedded subdocument and array. This is the hard limit that rules out embedding an unbounded array: comments on a viral post, events on a busy sensor, anything that grows without a cap will eventually hit it. Those relationships must be referenced into their own collection (or bucketed).
Use the $lookup stage in an aggregation pipeline. It performs a left outer join from one collection into another, matching localField against foreignField and writing the matches into an array field you name with as. For a single-match join you usually follow it with $unwind to flatten that array into a subdocument. Note that a $lookup is slower than reading embedded data, and MongoDB enforces no foreign keys, so a reference to a deleted document just returns no matches.
No. MongoDB does not enforce referential integrity. If you store an authorId on a post and then delete that author, the post still holds the now-dangling reference, and a $lookup against it returns an empty result. Keeping references valid (cascading deletes, cleanup jobs, or validation on write) is the application's responsibility, not the database's.
For reads, usually yes: embedded data comes back in a single document read with no join, and a single-document write is atomic. But embedding stops paying off when the embedded data grows without bound (you risk the 16 MB limit and pay to rewrite a large document on every change) or when the same entity is duplicated across many parents (a single update becomes many). At that point a reference plus a $lookup is the faster and cleaner model overall.
Store the reference on the many side: each child holds the parent's _id (a postId on every comment, a customerId on every order). That keeps the parent document small and fixed in size no matter how many children exist, and it lets you index the child collection on the parent key for fast, paged lookups.
Putting an array of child _ids on the parent instead works only when that array is bounded, and it reintroduces the unbounded-array problem the reference was meant to avoid. The exception is the subset pattern: keep a short array of the hot few on the parent and the full set on the many side.
Duplicate a field when the read cost of joining for it outweighs the write cost of keeping copies in sync, and when that field rarely changes. The extended reference pattern is exactly this: copy one or two hot fields (an author name, a product title) onto the referencing document next to the _id, so the common read skips the $lookup. You take on the job of updating the copies when the source changes, which is cheap if the field is near-static and expensive if it churns. Do not duplicate volatile data; reference it.
Use the Decimal128 type, created in mongosh with NumberDecimal("9.99") (always from a string). It stores amounts exactly with 34 digits of precision. For high-volume ledgers, store the integer count of cents in a NumberLong instead. Always pair the amount with a separate ISO 4217 currency field, and never store money as a BSON double.
Use { $round: ["$price", 2] } in an aggregation; the result keeps the input's Decimal128 type. On a tie (a trailing 5) it rounds to the nearest even value, so 0.125 goes to 0.12 and 0.135 goes to 0.14. That is banker's rounding (round half to even), the same rule the IEEE 754 decimal standard uses. Round on a Decimal128 input, never a double.
No. A UUID is stored inside the general-purpose Binary type, with the subtype tag set to 4 to mark the 16 bytes as a UUID. That is what mongosh's UUID() helper and each driver's UUID class produce.
BSON equality is type-aware: a String never equals a Binary. If the field holds a subtype-4 Binary, a query like { token: "3b241101-..." } matches nothing. Wrap the value in UUID("...") in mongosh, or the driver's UUID type in code.
It inverts the default. In a relational database you normalize first (one entity per table, join on read) and denormalize only when joins hurt. In MongoDB you start by embedding related data in the document that reads it, and reach for references only when cardinality, duplication, or the 16 MB limit force it. You model around how the application queries the data, not around a normalized schema.
See also
- Storing money in MySQL: DECIMAL vs BIGINT cents is the relational version of the money decision above.
- Storing a UUID in PostgreSQL, where there is a real native
uuidtype to reach for. - Running MongoDB in Docker gets you a throwaway instance to test an embedded-versus-referenced schema before you commit to it.
- Storing JSON with the jsonb type in PostgreSQL is the relational answer to document-shaped data, useful when you are weighing Mongo against Postgres.
- Storing JSON in MySQL shows how MySQL's native JSON column compares to nesting subdocuments in MongoDB.
Sources
Authoritative references this article was fact-checked against.
- MongoDB Manual: Data Modelingmongodb.com
- MongoDB Manual: Data Model Design (embedded vs normalized)mongodb.com
- MongoDB Manual: Limits and Thresholds (16 MB BSON document size)mongodb.com
- MongoDB Manual: $lookup (aggregation) referencemongodb.com
- MongoDB Manual: Model Monetary Datamongodb.com
- MongoDB Manual: BSON Types (decimal, double, long, Binary subtypes, UUID, ObjectId)mongodb.com
- MongoDB Manual: Extended JSON ($numberDecimal, $numberLong)mongodb.com
- MongoDB Manual: 3.4 Release Notes (Decimal128 introduced)mongodb.com
- MongoDB Manual: $round aggregation operator (round half to even)mongodb.com
- MongoDB Manual: UUID() method in mongoshmongodb.com
- MongoDB Specifications: Handling of Native UUID Types (subtype 3 vs 4, byte order)github.com
- PyMongo Driver: Universally Unique IDs (uuidRepresentation, STANDARD vs legacy)mongodb.com





