MongoDB Tutorial 0/120 lessons ~6 min read Lesson 91

    MongoDB in E-Commerce

    E-commerce is MongoDB's flagship use case.

    Course progress0%
    Focus
    5 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    E-commerce is MongoDB's flagship use case. From eBay's product catalog to Forbes' commerce stack and countless Shopify-style platforms, MongoDB powers product search, cart, checkout, order history and analytics — all from a flexible document model that matches how product data actually looks.

    The document model is a natural fit: every product has different attributes (size, color, voltage, ISBN, expiration date), every cart embeds line items, every order embeds shipping + payment snapshots that must never change post-fact.

    Understanding the topic

    The core e-commerce collections:

    • products — embed variants, specs and price tiers; index on slug, categoryId, tags.
    • inventory — separate collection updated atomically with $inc; avoids embedding stock in the catalog.
    • carts — short-lived, embedded line items keyed by userId or anonymous sessionId.
    • orders — immutable snapshots of cart + price + address + tax at checkout time.
    • reviews — referenced (not embedded) so reviews can be moderated and paginated independently.
    • search — Atlas Search index over products for typo-tolerant, faceted, real-time search.

    Informative example

    Atomic "add to cart with inventory check" — multi-document transaction:

    js
    const session = client.startSession();
    await session.withTransaction(async () => {
    const stock = await db.inventory.findOneAndUpdate(
    { sku, available: { $gte: qty } },
    { $inc: { available: -qty, reserved: qty } },
    { session, returnDocument: "after" }
    );
    if (!stock) throw new OutOfStockError(sku);
    await db.carts.updateOne(
    { userId },
    { $push: { items: { sku, qty, price: stock.price } },
    $set: { updatedAt: new Date() } },
    { upsert: true, session }
    );
    });

    Real-world use

    Coinbase Commerce, ASOS, Sega Store and 60% of the Internet Retailer Top 1000 use MongoDB for catalog and order data. Atlas Search replaces Elasticsearch entirely for many of them.

    Best practices

    • Snapshot price + tax + shipping into the order document at checkout — never recompute.
    • Inventory in its own collection, updated atomically — never $inc embedded stock.
    • Use Atlas Search facets for filter UIs (brand, size, price range) — no separate search engine needed.
    • Add a unique index on orders.orderNumber to make idempotent retries safe.
    Ready to mark this lesson complete?Track your journey across the entire course.