TExcelTAD
Home › MongoDB › Data Modeling: Embed or Reference

Data Modeling: Embed or Reference

In a relational database you normalise data into tables and join them at query time. In MongoDB the central design question is different: should related data be embedded in one document, or stored in separate documents that reference each other?

The guiding principle: data that is accessed together should be stored together. Design for the queries your application runs most.

Embedding

The sample store embeds an order's line items and a customer's address:

js
{ _id: 1002, customerId: 3, status: 'delivered',
  items: [ { productId: 3, name: 'Ethiopia Yirgacheffe', qty: 1, price: 27 }, … ],
  total: 45 }

One read returns the complete order, and an update to the order (including its items) is atomic, because it touches a single document.

mongosh · try it yourself
const order = db.orders.findOne({ _id: 1002 });
print(order.items.length, 'items, total', order.total);
// adding an item and updating the total happen together, atomically
db.orders.updateOne({ _id: 1002 }, {
  $push: { items: { productId: 19, name: 'Salted Pretzels', qty: 1, price: 3.5 } },
  $inc: { total: 3.5 }
});
print(db.orders.findOne({ _id: 1002 }, { total: 1, n: { $size: '$items' } }));
2 items, total 45
{ _id: 1002, total: 48.5, n: 3 }

Embed when:

  • the child data is mostly read with the parent (an order and its items),
  • the relationship is "contains" or one-to-few (a customer's few addresses),
  • the embedded array has a bounded size.

Referencing

Orders refer to customers by customerId instead of embedding them. A customer has a life of their own (profile edits, many orders over years), and embedding every order inside the customer would grow the document without limit.

mongosh · try it yourself
// two queries: the "application-level join"
const customer = db.customers.findOne({ _id: 5 }, { name: 1 });
const orders = db.orders.find({ customerId: 5 }, { total: 1 }).sort({ _id: 1 }).toArray();
print(customer.name, 'has', orders.length, 'orders:', orders.map(o => o._id));
Margaret Hamilton has 3 orders: [ 1004, 1010, 1020 ]

Or one round trip with $lookup. Reference when:

  • the related data is large or grows without bound (all orders of a customer, comments on a popular post),
  • it is shared by many parents (products appear in many orders),
  • it is often read or updated on its own.

Duplicating on purpose

Each order item stores a copy of the product's name and price. That isn't sloppy: it is the price at the time of purchase, and it lets order pages render without touching the products collection. When the product's price changes, old orders must not change:

mongosh · try it yourself
db.products.updateOne({ _id: 3 }, { $set: { price: 29 } });
print('catalogue price now:', db.products.findOne({ _id: 3 }).price);
print('price paid in 1002: ', db.orders.findOne({ _id: 1002 }).items.find(i => i.productId === 3).price);
catalogue price now: 29
price paid in 1002:  27

Duplicate fields that rarely change or should keep their historical value. If a duplicated field must stay in sync (say, a product's name shown in carts), you need to update every copy, often with updateMany.

Relationship patterns

Relationship Typical model Example
One-to-one embed customer and their address
One-to-few embed an array product and its tags
One-to-many reference from the "many" side orders.customerId
One-to-squillions reference, never embed a sensor and millions of readings
Many-to-many arrays of references on one or both sides students.courseIds, courses.studentIds

Useful schema patterns

  • Subset pattern: embed only the most recent or most important part (the last 5 reviews in the product) and keep the rest in a separate collection.
  • Computed pattern: store values that are expensive to compute, such as total on orders or a product's average rating, and update them on write.
  • Bucket pattern: group many small items into one document per time range, for example one document per sensor per hour.
  • Extended reference: copy the few fields you always display (customer name) next to the reference (customerId).

The subset pattern in action, keeping only the three newest reviews inside the product:

mongosh · try it yourself
const reviews = [
  { stars: 5, text: 'Bright and floral' },
  { stars: 4, text: 'Great as pour-over' },
  { stars: 5, text: 'My favourite' },
  { stars: 3, text: 'A bit too acidic for me' }
];
for (const r of reviews) {
  db.products.updateOne({ _id: 3 }, { $push: { recentReviews: { $each: [r], $slice: -3 } } });
}
print(db.products.findOne({ _id: 3 }, { name: 1, recentReviews: 1 }));
{
  _id: 3,
  name: 'Ethiopia Yirgacheffe',
  recentReviews: [
    { stars: 4, text: 'Great as pour-over' },
    { stars: 5, text: 'My favourite' },
    { stars: 3, text: 'A bit too acidic for me' }
  ]
}

Warning: Unbounded arrays are the classic MongoDB modeling mistake. A document is limited to 16 MB, and huge arrays make every read and update of the document slow. If an array can grow forever, it belongs in its own collection.

Test yourself

Which is the best fit for embedding?

  1. All orders ever placed by a customer
  2. The line items of one order
  3. Every reading of a sensor
  4. All users who liked a post

Why does each order item copy the product's price?

  1. MongoDB can't join
  2. To keep the price paid at purchase time, even if the product's price changes later
  3. To save disk space
  4. Because of the 16 MB limit

What is a key benefit of embedding related data?

  1. Unlimited document size
  2. Reads need one query and updates of the whole are atomic
  3. No indexes are needed
  4. Data can't be duplicated