Sikau

MongoDB · Day 6 · about 30 min

Embed or reference?

The core MongoDB design decision.

Design for how you read

In SQL you normalise first. In MongoDB you design around your app's queries: data read together usually lives together (embedding), while data shared or growing without limit lives apart and is linked by id (referencing).

Two shapes for orders

const order = db.orders.findOne({ customer: "c1", status: "served" });
printjson(order.items);

const customer = db.customers.findOne({ _id: order.customer });
print("Ordered by", customer.name, "in", customer.city);

print("Order total:", order.items.reduce((s, i) => s + i.qty * i.price, 0));
  • Embed when: read together, owned by the parent, bounded in size (an order's items, a user's addresses).
  • Reference when: shared across documents, updated independently, or unbounded (a dish's 10,000 reviews).
  • A document can be at most 16 MB — never let arrays grow forever.
  • Join referenced data with a second query or the $lookup aggregation stage (Unit 3).

The rest of this lesson

  • Start from the screensexplain
  • The unbounded array trapexplain
  • Embed or reference?predict
  • Where does it live?match
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of MongoDB