Structure MongoDB Product Data

MongoDBMongoDBBeginner
Practice Now

Introduction

In this lab, you will learn how to design a structured MongoDB document schema for product data in an e-commerce system. The lab covers the essential steps, including creating a product schema, adding category information, including price details, setting stock levels, and tracking product status. By the end of this lab, you will have a comprehensive understanding of how to model product data effectively in a MongoDB database.

The lab starts by creating a product schema that captures various product details, such as name, category, brand, pricing, stock information, specifications, and metadata. You will learn how to leverage MongoDB's flexible document structure to represent complex product data. Additionally, the lab demonstrates how to manage product status and enable efficient filtering and display of product information.


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`") mongodb/RelationshipsGroup -.-> mongodb/link_related_documents("`Link Related Documents`") subgraph Lab Skills mongodb/create_database_collection -.-> lab-422092{{"`Structure MongoDB Product Data`"}} mongodb/update_document -.-> lab-422092{{"`Structure MongoDB Product Data`"}} mongodb/manage_array_elements -.-> lab-422092{{"`Structure MongoDB Product Data`"}} mongodb/design_order_schema -.-> lab-422092{{"`Structure MongoDB Product Data`"}} mongodb/create_embedded_documents -.-> lab-422092{{"`Structure MongoDB Product Data`"}} mongodb/create_document_references -.-> lab-422092{{"`Structure MongoDB Product Data`"}} mongodb/link_related_documents -.-> lab-422092{{"`Structure MongoDB Product Data`"}} end

Create Product Schema

In this step, you'll learn how to design a structured MongoDB document schema for product data. We'll create a flexible and comprehensive schema that can represent various types of products in an e-commerce system.

First, let's start the MongoDB shell:

mongosh

Now, let's create a database for our product catalog:

use product_catalog

We'll design a product schema that includes multiple fields to capture comprehensive product information:

db.products.insertOne({
  name: "Wireless Noise-Canceling Headphones",
  category: "Electronics",
  subcategory: "Audio",
  brand: "TechSound",
  price: {
    base: 199.99,
    currency: "USD",
    discount: {
      percentage: 10,
      active: true
    }
  },
  stock: {
    total: 500,
    available: 450,
    warehouse: "Main Distribution Center"
  },
  specifications: {
    color: ["Black", "Silver"],
    batteryLife: "30 hours",
    connectivity: ["Bluetooth 5.0", "3.5mm Jack"]
  },
  status: {
    inStock: true,
    featured: false,
    new: true
  },
  metadata: {
    sku: "TECH-SOUND-NC-001",
    dateAdded: new Date(),
    lastUpdated: new Date()
  }
});

Let's break down the schema:

  1. Basic Product Information:

    • name: Product title
    • category and subcategory: Hierarchical classification
    • brand: Manufacturer information
  2. Pricing Details:

    • Nested price object with base price, currency, and discount information
  3. Stock Management:

    • stock object tracking total and available inventory
    • Warehouse location
  4. Product Specifications:

    • Flexible specifications object for detailed product attributes
    • Supports multiple values (like colors)
  5. Product Status:

    • status object for quick filtering and display logic
  6. Metadata:

    • Tracking additional information like SKU and timestamps

To verify our document, let's retrieve it:

db.products.find({ name: "Wireless Noise-Canceling Headphones" });

Add Category Info

In this step, we'll expand our product schema by creating a comprehensive category management system. We'll demonstrate how to add detailed category information to our product documents and create a separate categories collection for better organization.

First, let's continue in the MongoDB shell:

mongosh product_catalog

Let's create a dedicated categories collection to manage product categories hierarchically:

db.categories.insertMany([
  {
    _id: "electronics",
    name: "Electronics",
    description: "All electronic devices and gadgets",
    parent: null,
    subcategories: ["audio", "computers", "smartphones"]
  },
  {
    _id: "audio",
    name: "Audio",
    description: "Sound and audio equipment",
    parent: "electronics",
    attributes: ["wireless", "noise-canceling", "battery-life", "connectivity"]
  }
]);

Now, let's update our previous product document to reference these categories:

db.products.updateOne(
  { name: "Wireless Noise-Canceling Headphones" },
  {
    $set: {
      categoryRef: {
        main: "electronics",
        sub: "audio"
      },
      categoryDetails: {
        path: ["electronics", "audio"],
        taxonomyVersion: "1.0"
      }
    }
  }
);

Let's verify the updated product document:

db.products.findOne({ name: "Wireless Noise-Canceling Headphones" });

This approach provides several benefits:

  1. Separate category management
  2. Hierarchical category structure
  3. Flexible attribute tracking
  4. Easy categorization and filtering

Include Price Details

In this step, we'll enhance our product schema by creating a comprehensive pricing structure that supports multiple pricing scenarios and currency management.

First, let's continue in the MongoDB shell:

mongosh product_catalog

We'll create a more detailed pricing model with multiple pricing strategies:

db.products.updateOne(
  { name: "Wireless Noise-Canceling Headphones" },
  {
    $set: {
      pricing: {
        base: {
          amount: 199.99,
          currency: "USD"
        },
        retail: {
          amount: 219.99,
          currency: "USD"
        },
        discounts: [
          {
            type: "SEASONAL",
            percentage: 10,
            startDate: new Date("2024-01-01"),
            endDate: new Date("2024-01-31")
          },
          {
            type: "LOYALTY",
            percentage: 5,
            conditions: "For members with 1+ year membership"
          }
        ],
        taxRates: {
          standard: 0.08,
          reduced: 0.05
        },
        priceHistory: [
          {
            date: new Date("2023-12-01"),
            amount: 189.99
          },
          {
            date: new Date("2024-01-01"),
            amount: 199.99
          }
        ]
      }
    }
  }
);

Let's create a separate pricing collection for more complex pricing strategies:

db.pricing_rules.insertOne({
  productId: "TECH-SOUND-NC-001",
  dynamicPricing: {
    enabled: true,
    algorithm: "supply-demand",
    minPrice: 150.0,
    maxPrice: 250.0
  },
  bulkPricing: [
    {
      quantity: { min: 1, max: 10 },
      discount: 0
    },
    {
      quantity: { min: 11, max: 50 },
      discount: 0.05
    },
    {
      quantity: { min: 51 },
      discount: 0.1
    }
  ]
});

Verify the updated product pricing:

db.products.findOne({ name: "Wireless Noise-Canceling Headphones" });

Set Stock Levels

In this step, we'll develop a sophisticated inventory management system for tracking product stock across multiple warehouses and locations.

First, let's continue in the MongoDB shell:

mongosh product_catalog

We'll create a comprehensive stock management schema:

db.products.updateOne(
  { name: "Wireless Noise-Canceling Headphones" },
  {
    $set: {
      inventory: {
        total: {
          quantity: 1000,
          unit: "pieces"
        },
        warehouses: [
          {
            name: "Main Distribution Center",
            location: "New York",
            quantity: 500,
            status: "primary"
          },
          {
            name: "West Coast Warehouse",
            location: "Los Angeles",
            quantity: 300,
            status: "secondary"
          },
          {
            name: "Online Fulfillment Center",
            location: "Chicago",
            quantity: 200,
            status: "backup"
          }
        ],
        tracking: {
          minimumStockLevel: 100,
          restockThreshold: 250,
          lastRestocked: new Date()
        },
        reservations: [
          {
            type: "online_orders",
            quantity: 50,
            reservedUntil: new Date(Date.now() + 24 * 60 * 60 * 1000)
          }
        ]
      }
    }
  }
);

Let's create a separate inventory tracking collection:

db.inventory_logs.insertOne({
  productId: "TECH-SOUND-NC-001",
  transactionHistory: [
    {
      date: new Date(),
      type: "initial_stock",
      quantity: 1000,
      source: "manufacturer",
      notes: "Initial product launch inventory"
    }
  ],
  stockAdjustments: [
    {
      date: new Date(),
      reason: "Seasonal Preparation",
      quantityAdjusted: 100,
      direction: "increase"
    }
  ]
});

Verify the updated product inventory:

db.products.findOne({ name: "Wireless Noise-Canceling Headphones" });

Track Product Status

In this step, we'll implement a comprehensive product status tracking system that provides detailed insights into product lifecycle, marketing status, and performance metrics.

First, let's continue in the MongoDB shell:

mongosh product_catalog

We'll update our product document with an advanced status tracking mechanism:

db.products.updateOne(
  { name: "Wireless Noise-Canceling Headphones" },
  {
    $set: {
      productStatus: {
        lifecycle: {
          stage: "active",
          introduced: new Date("2024-01-01"),
          expectedEndOfLife: new Date("2025-12-31")
        },
        marketingStatus: {
          featured: true,
          newArrival: false,
          onSale: true,
          promotionActive: true
        },
        performanceMetrics: {
          salesVolume: {
            monthly: 1500,
            quarterly: 4500,
            yearly: 18000
          },
          customerRatings: {
            average: 4.7,
            totalReviews: 250,
            recommendationRate: 0.92
          }
        },
        complianceAndCertification: {
          regulatoryApprovals: ["FCC", "CE", "RoHS"],
          warrantyInfo: {
            duration: "2 years",
            type: "manufacturer"
          }
        },
        digitalPresence: {
          websiteVisibility: {
            pageViews: 50000,
            uniqueVisitors: 15000
          },
          ecommercePlatforms: ["company_website", "amazon", "best_buy"]
        }
      }
    }
  }
);

Create a separate collection for product status tracking and historical data:

db.product_status_history.insertOne({
  productId: "TECH-SOUND-NC-001",
  statusChanges: [
    {
      date: new Date(),
      previousStatus: "development",
      newStatus: "active",
      reason: "Product launch",
      updatedBy: "product_management_team"
    }
  ],
  performanceSnapshots: [
    {
      date: new Date(),
      salesVolume: 1500,
      customerSatisfaction: 4.7
    }
  ]
});

Verify the updated product status:

db.products.findOne({ name: "Wireless Noise-Canceling Headphones" });

Summary

In this lab, you learned how to design a structured MongoDB document schema for product data. You created a flexible and comprehensive schema that can represent various types of products in an e-commerce system. The schema includes fields for basic product information, pricing details, stock management, product specifications, status, and metadata. This allows for efficient storage and retrieval of detailed product data within a MongoDB database.

The schema covers key aspects of product data, such as hierarchical categorization, pricing with discounts, inventory tracking, detailed specifications, and status indicators. This structured approach enables effective product management and supports various use cases in an e-commerce application.

Other MongoDB Tutorials you may like