Design MongoDB Order Schema

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, we will design a MongoDB order schema for an e-commerce application. We will start by creating a structured document to store essential order information, including the order ID, customer details, order date, and status. Then, we will expand the customer details by adding a nested document structure to capture rich customer information such as personal information and address. Finally, we will include order items, payment information, and handle order status updates to create a comprehensive order schema.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL mongodb(("`MongoDB`")) -.-> mongodb/BasicOperationsGroup(["`Basic Operations`"]) mongodb(("`MongoDB`")) -.-> mongodb/DataTypesGroup(["`Data Types`"]) mongodb(("`MongoDB`")) -.-> mongodb/SchemaDesignGroup(["`Schema Design`"]) mongodb(("`MongoDB`")) -.-> mongodb/ArrayandEmbeddedDocumentsGroup(["`Array and Embedded Documents`"]) mongodb(("`MongoDB`")) -.-> mongodb/RelationshipsGroup(["`Relationships`"]) mongodb/BasicOperationsGroup -.-> mongodb/create_database_collection("`Create Database and Collection`") mongodb/BasicOperationsGroup -.-> mongodb/update_document("`Update Document`") mongodb/DataTypesGroup -.-> mongodb/manage_array_elements("`Manage Array Elements`") mongodb/SchemaDesignGroup -.-> mongodb/design_order_schema("`Design Order Schema`") mongodb/ArrayandEmbeddedDocumentsGroup -.-> mongodb/create_embedded_documents("`Create Embedded Documents`") mongodb/RelationshipsGroup -.-> mongodb/create_document_references("`Create Document References`") subgraph Lab Skills mongodb/create_database_collection -.-> lab-422080{{"`Design MongoDB Order Schema`"}} mongodb/update_document -.-> lab-422080{{"`Design MongoDB Order Schema`"}} mongodb/manage_array_elements -.-> lab-422080{{"`Design MongoDB Order Schema`"}} mongodb/design_order_schema -.-> lab-422080{{"`Design MongoDB Order Schema`"}} mongodb/create_embedded_documents -.-> lab-422080{{"`Design MongoDB Order Schema`"}} mongodb/create_document_references -.-> lab-422080{{"`Design MongoDB Order Schema`"}} end

Create Order Structure

In this step, we'll design a MongoDB order schema for an e-commerce application. We'll start by understanding how to create a structured document for storing order information.

First, open the MongoDB shell by launching the terminal and typing:

mongosh

Now, let's create a database for our e-commerce orders:

use ecommerce_orders

We'll design an order structure with key fields that capture essential order information:

db.orders.insertOne({
  order_id: "ORD-2024-001",
  customer: {
    customer_id: "CUST-123",
    name: "John Doe",
    email: "[email protected]"
  },
  order_date: new Date(),
  status: "pending"
});

Let's break down the order structure:

  • order_id: A unique identifier for the order
  • customer: An embedded document with customer details
  • order_date: Timestamp of the order creation
  • status: Current status of the order

Add Customer Details

In this step, we'll expand our order schema by adding more comprehensive customer details to our MongoDB document. We'll demonstrate how to create a nested document structure that captures rich customer information.

First, ensure you're still in the MongoDB shell from the previous step. If not, start it again:

mongosh ecommerce_orders

Let's update our existing order document with more detailed customer information:

db.orders.updateOne(
  { order_id: "ORD-2024-001" },
  {
    $set: {
      customer: {
        customer_id: "CUST-123",
        personal_info: {
          first_name: "John",
          last_name: "Doe",
          email: "[email protected]",
          phone: "+1-555-123-4567"
        },
        address: {
          street: "123 Tech Lane",
          city: "San Francisco",
          state: "CA",
          postal_code: "94105",
          country: "USA"
        },
        contact_preferences: {
          email_notifications: true,
          sms_notifications: false
        }
      }
    }
  }
);

Let's verify the updated document:

db.orders.findOne({ order_id: "ORD-2024-001" });

This expanded customer schema provides:

  • Detailed personal information
  • Complete address details
  • Contact preferences
  • Nested document structure for better organization

The nested structure allows for more flexible and comprehensive data storage compared to flat schemas.

Include Order Items

In this step, we'll enhance our order schema by adding a comprehensive list of order items. We'll demonstrate how to create an array of items within our order document, capturing detailed product information.

Ensure you're still in the MongoDB shell:

mongosh ecommerce_orders

Now, let's update our order document to include a detailed items array:

db.orders.updateOne(
  { order_id: "ORD-2024-001" },
  {
    $set: {
      items: [
        {
          product_id: "PROD-001",
          name: "Wireless Headphones",
          category: "Electronics",
          price: 129.99,
          quantity: 1,
          subtotal: 129.99
        },
        {
          product_id: "PROD-002",
          name: "Laptop Sleeve",
          category: "Accessories",
          price: 24.5,
          quantity: 2,
          subtotal: 49.0
        }
      ],
      total_items: 2,
      subtotal: 178.99,
      tax: 14.32,
      total: 193.31
    }
  }
);

Let's verify the updated document:

db.orders.findOne({ order_id: "ORD-2024-001" });

Key features of this items schema:

  • Array of items with detailed product information
  • Each item includes product ID, name, category, price, and quantity
  • Calculated subtotals for individual items
  • Overall order totals (items count, subtotal, tax, total)

The array structure allows for multiple items in a single order and provides flexibility for different product types.

Set Payment Info

In this step, we'll add detailed payment information to our order schema. We'll demonstrate how to create a comprehensive payment structure that captures various payment-related details.

Ensure you're still in the MongoDB shell:

mongosh ecommerce_orders

Let's update our order document with payment information:

db.orders.updateOne(
  { order_id: "ORD-2024-001" },
  {
    $set: {
      payment: {
        method: "credit_card",
        card_info: {
          last_four: "4567",
          card_type: "Visa",
          payment_network: "Visa"
        },
        transaction: {
          transaction_id: "TXN-2024-001",
          amount: 193.31,
          currency: "USD",
          timestamp: new Date(),
          status: "completed"
        },
        billing_address: {
          street: "123 Tech Lane",
          city: "San Francisco",
          state: "CA",
          postal_code: "94105",
          country: "USA"
        }
      }
    }
  }
);

Let's verify the updated document:

db.orders.findOne({ order_id: "ORD-2024-001" });

Key features of this payment schema:

  • Payment method details
  • Masked card information
  • Transaction specifics
  • Billing address
  • Secure handling of sensitive payment data

The nested structure provides a comprehensive view of the payment while keeping sensitive information secure.

Handle Order Status

In this step, we'll enhance our order schema by implementing a comprehensive order status tracking mechanism. We'll demonstrate how to create a detailed status tracking system that captures the order's lifecycle.

Ensure you're still in the MongoDB shell:

mongosh ecommerce_orders

Let's update our order document with an advanced status tracking structure:

db.orders.updateOne(
  { order_id: "ORD-2024-001" },
  {
    $set: {
      status_tracking: {
        current_status: "processing",
        status_history: [
          {
            status: "created",
            timestamp: new Date(Date.now() - 86400000), // 24 hours ago
            notes: "Order initially placed"
          },
          {
            status: "processing",
            timestamp: new Date(),
            notes: "Order is being prepared for shipment"
          }
        ],
        fulfillment: {
          warehouse: "SF-01",
          estimated_shipping_date: new Date(Date.now() + 172800000), // 2 days from now
          shipping_method: "standard"
        },
        tracking_number: null,
        expected_delivery: new Date(Date.now() + 432000000) // 5 days from now
      }
    }
  }
);

Let's verify the updated document:

db.orders.findOne({ order_id: "ORD-2024-001" });

Key features of this status tracking schema:

  • Current status of the order
  • Comprehensive status history
  • Fulfillment details
  • Estimated shipping and delivery dates
  • Flexible tracking mechanism

The nested structure allows for detailed tracking and easy status updates.

Summary

In this lab, we learned how to design a MongoDB order schema for an e-commerce application. First, we created a structured document to store essential order information, including a unique order ID, customer details, order date, and order status. Then, we expanded the customer details by adding a nested document structure to capture rich customer information, such as personal information and address. Additionally, we included order items, payment information, and handled order status updates. By the end of this lab, we had a comprehensive MongoDB order schema that can effectively manage e-commerce orders.

Other MongoDB Tutorials you may like