#Embedding vs referencing
In a relational database you design the schema from the data: normalise it into tables so that every fact lives in one place, then join at query time. In MongoDB you design from the queries: the guiding principle is "data that is accessed together should be stored together". You have two tools. Embedding puts related data inside the parent document (an order's line items inside the order). Referencing stores the related data in its own collection and keeps its _id in the parent (the order stores customerId), the way a foreign key would.
My notes say "very important: embed if possible", and call the two options normalising (a separate collection) and denormalising (the same document). The mental model is a filing folder. Embedding is putting the invoice, the delivery note and the packing list in one folder: grab the folder and you have everything, and you can update all of it in one go. Referencing is a folder with a note saying "customer details: see drawer C, file 17": the folder stays slim and the customer file is shared by every folder that mentions it, but reading the whole picture means a second trip to the cabinet.
This chapter's examples use the site's sample data as MongoDB collections, the same customers and orders as the Aggregation Pipeline chapter (the Starting data box below loads them; the original runs used a database called ch19, which is why ch19 appears in a few outputs). The orders collection already makes both choices: line items are embedded, the customer is referenced:
Starting dataThe sample customers and orders
The 6 customers and 8 orders this chapter starts from. Orders embed their line items (productId, qty, unitPrice):
db.customers.insertMany([
{ _id: 1, name: "Rohit", email: "rohit@example.com", city: "Toronto", createdAt: ISODate("2025-01-05T09:00:00Z") },
{ _id: 2, name: "Maya", email: "maya@example.com", city: "Mumbai", createdAt: ISODate("2025-01-20T14:30:00Z") },
{ _id: 3, name: "Liam", email: "liam@example.com", city: "London", createdAt: ISODate("2025-02-11T08:15:00Z") },
{ _id: 4, name: "Sofia", email: "sofia@example.com", city: null, createdAt: ISODate("2025-03-02T19:45:00Z") },
{ _id: 5, name: "Noah", email: "noah@example.com", city: "Toronto", createdAt: ISODate("2025-03-18T11:00:00Z") },
{ _id: 6, name: "Zara", email: "zara@example.com", city: "Dubai", createdAt: ISODate("2025-04-01T16:20:00Z") }
]);
db.orders.insertMany([
{ _id: 1, customerId: 1, status: "shipped", orderedAt: ISODate("2025-02-01T10:00:00Z"),
items: [ { productId: 1, qty: 1, unitPrice: 899 }, { productId: 7, qty: 2, unitPrice: 29 } ] },
{ _id: 2, customerId: 1, status: "paid", orderedAt: ISODate("2025-03-15T12:30:00Z"),
items: [ { productId: 5, qty: 1, unitPrice: 39 }, { productId: 6, qty: 1, unitPrice: 49 } ] },
{ _id: 3, customerId: 2, status: "shipped", orderedAt: ISODate("2025-02-10T09:20:00Z"),
items: [ { productId: 3, qty: 1, unitPrice: 799 }, { productId: 8, qty: 1, unitPrice: 249 } ] },
{ _id: 4, customerId: 3, status: "cancelled", orderedAt: ISODate("2025-02-14T18:00:00Z"),
items: [ { productId: 2, qty: 1, unitPrice: 1299 } ] },
{ _id: 5, customerId: 3, status: "shipped", orderedAt: ISODate("2025-03-01T07:45:00Z"),
items: [ { productId: 6, qty: 2, unitPrice: 49 }, { productId: 7, qty: 1, unitPrice: 29 } ] },
{ _id: 6, customerId: 4, status: "pending", orderedAt: ISODate("2025-03-20T21:10:00Z"),
items: [ { productId: 8, qty: 1, unitPrice: 249 } ] },
{ _id: 7, customerId: 5, status: "paid", orderedAt: ISODate("2025-04-02T13:05:00Z"),
items: [ { productId: 1, qty: 1, unitPrice: 899 }, { productId: 5, qty: 3, unitPrice: 39 } ] },
{ _id: 8, customerId: 2, status: "shipped", orderedAt: ISODate("2025-04-05T15:40:00Z"),
items: [ { productId: 7, qty: 4, unitPrice: 29 } ] }
]);db.orders.findOne({ _id: 1 })
db.orders.aggregate([
{ $match: { _id: 1 } },
{ $lookup: { from: "customers", localField: "customerId", foreignField: "_id", as: "customer",
pipeline: [ { $project: { _id: 0, name: 1, email: 1 } } ] } },
{ $set: { customer: { $first: "$customer" } } },
{ $project: { items: 0 } }
]){
_id: 1,
customerId: 1,
status: 'shipped',
orderedAt: ISODate('2025-02-01T10:00:00.000Z'),
items: [
{ productId: 1, qty: 1, unitPrice: 899 },
{ productId: 7, qty: 2, unitPrice: 29 }
]
}
[
{
_id: 1,
customerId: 1,
status: 'shipped',
orderedAt: ISODate('2025-02-01T10:00:00.000Z'),
customer: { name: 'Rohit', email: 'rohit@example.com' }
}
]- One
findOnereturns the order with all its lines: no join, one read, one index lookup on_id. In MySQL the same data needsordersjoined toorder_items. - The items are embedded because they belong to the order: they're always read with it, never on their own, created with it, and bounded (an order has a handful of lines, not millions). Each line also stores
unitPrice, the price at the time of sale, which must not change when the product's price does. - The customer is referenced by
customerIdbecause a customer exists independently, has many orders, and changes (email, address). Embedding a copy of the customer in every order would mean updating every order when the customer moves. - Reading the customer with the order needs a
$lookup(or a second query).$firstturns the joined one-element array into a plain sub-document. - So one collection uses both techniques, chosen per relationship. That is the normal case: the question is never "embed or reference?" for the whole schema, but for each relationship.
A write to a single document is atomic in MongoDB, including everything embedded in it. Adding a line to an order and changing its status is one operation that either fully happens or doesn't, with no transaction:
db.orders.updateOne({ _id: 2 }, { $push: { items: { productId: 7, qty: 1, unitPrice: 29 } }, $set: { status: "paid" } }).modifiedCount
db.orders.updateOne({ _id: 2 }, { $pull: { items: { productId: 7 } } }).modifiedCount1
1- The first update appends a charger to order 2's
itemsand setsstatusin the same write. No reader can ever see the new line without the new status, or the other way round. - With referenced line items (an
order_itemscollection), the same change would be two writes to two collections, and keeping them consistent would need a multi-document transaction (see Multi-document transactions). - The second update removes the line again, so the sample data stays as it was.
- This is a big reason the MongoDB docs push embedding: well-designed documents make most transactions unnecessary.
| Embed when… | Reference when… |
|---|---|
| The child is read together with the parent | The child is often read on its own |
| The child belongs to one parent only | The child is shared by many parents (many-to-many) |
| The number of children is small and bounded | The number of children is large or grows without limit |
| The child rarely changes, or changes with the parent | The child changes often and independently |
| You want atomic updates of parent and child | The combined document would approach 16 MB |
A useful middle ground is the extended reference: keep the reference and copy the few fields you need for display (an order stores customerId plus customerName), accepting that those copies can be slightly stale. See Schema design patterns.
A blog has posts and comments. A post page shows the post and its comments. Some posts get 5 comments, a few viral ones get 200,000. Users also have a "my comments" page. Embed the comments in the post?
Show answer
Not entirely. Reference them (a comments collection with postId, indexed), and optionally embed a subset: the latest 10 comments in the post for fast first page loads.
- Read together: yes, the post page shows comments, which argues for embedding.
- But the count is unbounded: 200,000 comments of a few hundred bytes would break the 16 MB limit, and long before that every new comment rewrites a huge document (measured in the next topic).
- The "my comments" page reads comments on their own, across posts, which a separate collection with an index on
{ authorId: 1, createdAt: -1 }serves directly. - The subset pattern gives most of the read benefit of embedding:
$pushwith$slice: -10keeps the last 10 in the post, and the full list is paged fromcomments.