Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 70 ยท Schema design

Case Study: Modeling an Online Shop

Design a MongoDB schema for an online shop step by step: list access patterns, shape products, orders and reviews, and compare the result with a relational design.

Schema design in MongoDB starts from a different question than relational design. Instead of asking "what are the entities and how do I normalize them?", you ask "what will the application read and write, and how often?" The answers decide what to embed, what to reference and what to copy. In this lesson we model a small online shop from scratch, using the ideas from Embedding vs Referencing, Schema Design Patterns and Modeling Relationships.

The commands shown in mongosh blocks are real MongoDB. The runnable examples are JavaScript stand-ins over arrays of documents (see The Practice Engine Used in This Tutorial), so you can follow every step of the reasoning and see the results.

Design in four steps

List the pages What screens and jobs does the shop have?
Estimate volume Reads or writes? How many per second?
Shape documents Embed what is read together.
Revisit Check each query against the design.
1 / 2

Step 1: list the access patterns

Write down what the application actually does, with a rough frequency. For our shop:

Operation Frequency Needs
Show a product page very high (reads) product details, average rating, a few reviews
Browse a category high name, price, thumbnail for many products
Place an order medium (writes) all items and prices as they were at that moment
Show "my orders" medium a customer's orders, newest first
Add a review low append and update the rating summary
Revenue report rare, offline totals by month and category

This table is the design. The product page dominates, so it should need one read. Orders are written once and then mostly read, so they should be self-contained. Reviews grow without bound on popular products, so they cannot all live inside the product.

Step 2: products

Products differ a lot (shoes have sizes, laptops have RAM), which suits flexible documents. The page needs the specs and the rating, so those live in the product. Reviews are different: a popular product might have 50,000 of them. We apply the subset pattern: keep the newest few reviews in the product for the page, keep all reviews in their own collection, and store precomputed reviewCount and ratingSum (the computed pattern) so the average needs no scan.

JavaScript
// real mongosh: one product document answers the whole product page
{
  _id: "p100",
  name: "Trail Shoe",
  category: "shoes",
  price: 89,
  attrs: { sizes: [40, 41, 42], waterproof: true },
  reviewCount: 3,
  ratingSum: 13,
  topReviews: [ { user: "Mia", stars: 5, text: "Grippy." } ]
}

The product page in the next TryIt is a single lookup by _id, then simple arithmetic. It also shows the full reviews collection behind it, which is queried only on the "see all reviews" page.

JS The product page in one read

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In real MongoDB the "add a review" step is two writes to two collections. If the second write can fail and drift must be impossible, wrap both in a transaction; if a slightly stale count is acceptable, a periodic recount repairs any drift.

Step 3: orders

An order is a record of what happened, so it should not change when the catalog does. If a shoe costs 89 today and 99 next month, last month's order must still say 89. That means we copy the name and price into each order line instead of referencing the live product. This duplication is deliberate; it is the extended reference pattern, and it makes an order readable with one lookup and no join.

JavaScript
{
  _id: "o900",
  customerId: "c1",
  placed: ISODate("2026-03-01T10:00:00Z"),
  status: "paid",
  items: [
    { productId: "p100", name: "Trail Shoe", category: "shoes", price: 89, qty: 2 },
    { productId: "p200", name: "Water Bottle", category: "outdoor", price: 14, qty: 1 }
  ],
  total: 192
}

An order has a handful of lines, so embedding them is safe. Index { customerId: 1, placed: -1 } and "my orders" becomes an indexed, pre-sorted read (see Designing Compound Indexes).

The stand-in below places orders, changes a product price afterwards, and runs a revenue-by-category report using the same stages you would use in an aggregation pipeline: unwind the items, group by category, and sum.

JS Orders keep a price snapshot

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first order still shows an 89 line even though the shoe now costs 99. If orders had only referenced the product, history would silently rewrite itself.

Step 4: check the design against the table

Walk through the access patterns once more:

  • Product page: one read, thanks to the subset and computed values. โœ”
  • Browse a category: an index on { category: 1, price: 1 } over small product documents. Keep the documents lean (do not embed hundreds of reviews). โœ”
  • Place an order: one insert; stock handling is a separate concern (see Atomicity and Single-Document Writes). โœ”
  • My orders: indexed query by customer. โœ”
  • Add a review: two writes, drift acceptable or transactional. โœ”
  • Revenue report: an aggregation over orders; for heavy reporting, copy data into a reporting store or use a pre-aggregated collection. โœ”

How this compares with a relational design

A normalized SQL design would have products, reviews, orders, order_items and customers, and the product page would join products with a review aggregate. That is a perfectly good design, and with indexes a database handles it well (see SQL joins). The document design trades flexibility for speed on known paths:

Concern Document design Relational design
Product page one read, no join join or several queries
Varying attributes natural (attrs) extra tables or JSON columns
Order history stays correct copied price in the order needs a stored price column in order_items too
New, unplanned report may need a pipeline or a copy usually one SQL query
Keeping counts correct your code (or a transaction) triggers or queries

Neither wins in general. MongoDB rewards you when you know your access patterns, and punishes you less for changing the shape of data than a rigid schema does, but it makes "ask any question of the data" less free. Revisit the design whenever the list of access patterns changes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What should drive a MongoDB schema design?

    Because there are no joins by default, you shape documents around how the data is read together and how often each operation runs.
  2. 2. Why does an order copy the product name and price instead of just storing the productId?

    An order is a historical record. A reference would show the current price, rewriting history, so the relevant fields are copied at purchase time.
  3. 3. Why keep reviews in their own collection and only a few in the product?

    This is the subset pattern: the hot read gets what it needs from one small document, and the full unbounded list lives elsewhere.
  4. 4. What is the cost of storing reviewCount and ratingSum in the product?

    Computed values speed up reads but must be updated whenever a review is added. Use a transaction if drift is not acceptable, or recount periodically.

Summary

  • Start from the access patterns table, not from entities: it tells you what must be one read.
  • Embed what is read together and bounded; keep unbounded collections (reviews) separate, with a small embedded subset for hot pages.
  • Store precomputed values (counts and sums) to avoid scans, and plan how to keep them correct.
  • Copy data that must stay as it was (order lines) instead of referencing live data.
  • Compare against a relational design honestly: documents are faster on planned paths, SQL is more flexible for unplanned questions.
  • The TryIts are JavaScript stand-ins; the mongosh documents are real MongoDB shapes.

Next, learn how writes stay safe under concurrency in Atomicity and Single-Document Writes.