Design a MongoDB schema for a scalable e-commerce platform

Instruction: Explain your schema design process and decisions for a high-traffic e-commerce platform, considering product catalog, user profiles, orders, and reviews. Address considerations for scalability, data retrieval efficiency, and potential future requirements.

Context: This question evaluates the candidate's ability to design a comprehensive and scalable MongoDB schema tailored to a complex, real-world application. It tests their understanding of MongoDB's document model, their foresight in anticipating future needs, and their ability to optimize for performance and scalability.

Updated

Official answer

Model the main access patterns: browse products, load a customer's order history, create an order and reserve inventory. Use separate collections for users, products, inventory, orders and unbounded reviews. Embed bounded line-item and address snapshots inside an order so later catalog/address edits do not rewrite purchase history.

A small illustrative order document can use string identifiers and integer minor units:

{
  "_id": "order-101",
  "userId": "user-7",
  "currency": "USD",
  "items": [
    {"productId": "product-3", "name": "Notebook", "quantity": 2, "unitPriceMinor": 350}
  ],
  "subtotalMinor": 700,
  "status": "pending"
}

This is a teaching example, not a complete checkout schema. Define taxes, discounts, shipping, currency precision and rounding separately. Integer minor units or appropriately handled Decimal128 avoid treating binary floating-point as exact money. Validate quantity, currency and totals, and preserve the price actually accepted at checkout.

Make inventory the authoritative stock record. Reserve with a conditional atomic update that cannot reduce stock below zero; coordinate reservation and order creation with a transaction where required. Use a unique idempotency key to reconcile checkout retries and payment-provider outcomes. Payment calls are not rolled back by a database transaction.

Index actual lookups, such as order history by user and creation time. Keep reviews and long histories outside growing parent arrays; MongoDB documents have a 16 MiB limit. Store password hashes through a vetted password-authentication system and payment-provider tokens as appropriate, rather than plaintext/reversibly encrypted passwords or unnecessary card data. Apply least privilege, validation and retention rules.

MongoDB data modeling, BSON types, limits

Related Questions