E-Commerce Platform Project
Build a Production-Ready MongoDB E-Commerce System from Scratch
π― Project Overview
Welcome to the most comprehensive MongoDB project! In this hands-on project, you'll build a complete e-commerce platform from the ground up, implementing every feature a modern online store needsβfrom user authentication to order processing, from product search to analytics dashboards.
π Meet TechBazaar: Your E-Commerce Platform
The Challenge: Sarah is launching TechBazaar, an online marketplace for electronics and gadgets. She needs a robust database system that can handle thousands of products, manage user accounts, process orders in real-time, and provide insights into sales patterns.
Your Mission: As the lead database architect, you'll design and implement the entire MongoDB backend for TechBazaar. The platform must support user registration, product catalog, shopping cart, order processing, customer reviews, and sales analytics.
π Learning Objectives
By completing this project, you will master:
ποΈ Schema Design
Learn to design embedded vs. referenced documents, handle relationships, and optimize for query patterns
π Advanced Queries
Master aggregation pipelines, text search, and complex filtering
β‘ Performance
Implement indexing strategies and query optimization
π Data Integrity
Use validation rules and atomic operations
π Analytics
Build complex aggregation pipelines for business intelligence
π Production Patterns
Apply industry best practices and scalability considerations
π Database Schema Design
Collection: users
{
_id: ObjectId,
email: String (unique, indexed),
passwordHash: String,
profile: {
firstName: String,
lastName: String,
phone: String
},
addresses: [{
street: String,
city: String,
state: String,
zipCode: String,
isDefault: Boolean
}],
createdAt: Date,
lastLogin: Date
}
Collection: products
{
_id: ObjectId,
name: String (text indexed),
description: String (text indexed),
category: String (indexed),
price: Number,
stock: Number,
images: [String],
specifications: Object,
rating: {
average: Number,
count: Number
},
tags: [String]
}
Collection: orders
{
_id: ObjectId,
orderNumber: String (unique),
userId: ObjectId (reference),
items: [{
productId: ObjectId,
productName: String,
quantity: Number,
price: Number,
subtotal: Number
}],
totalAmount: Number,
status: String,
shippingAddress: Object,
payment: {
method: String,
status: String,
transactionId: String
},
createdAt: Date,
deliveredAt: Date
}
π§ Initial Setup
1Create the Database
use techBazaar // Verify database creation db.getName() // Output: "techBazaar"
2Create Collections
db.createCollection("users")
db.createCollection("products")
db.createCollection("carts")
db.createCollection("orders")
db.createCollection("reviews")
db.createCollection("categories")
3Create Essential Indexes
// Users indexes
db.users.createIndex({ email: 1 }, { unique: true })
// Products indexes
db.products.createIndex({ name: "text", description: "text" })
db.products.createIndex({ category: 1, price: 1 })
// Orders indexes
db.orders.createIndex({ orderNumber: 1 }, { unique: true })
db.orders.createIndex({ userId: 1, createdAt: -1 })
db.orders.createIndex({ status: 1 })
π₯ Phase 1: User Management
User Registration
db.users.insertOne({
email: "john.doe@email.com",
passwordHash: "$2b$10$encrypted_password_hash",
profile: {
firstName: "John",
lastName: "Doe",
phone: "+1-555-0100"
},
addresses: [{
street: "123 Main Street",
city: "San Francisco",
state: "CA",
zipCode: "94102",
isDefault: true
}],
createdAt: new Date(),
lastLogin: new Date()
})
Find and Update User
db.users.updateOne(
{ email: "john.doe@email.com" },
{
$set: {
"profile.phone": "+1-555-9999",
lastLogin: new Date()
}
}
)
Add New Address
db.users.updateOne(
{ email: "john.doe@email.com" },
{
$push: {
addresses: {
street: "999 Business Blvd",
city: "Austin",
state: "TX",
zipCode: "78701",
isDefault: false
}
}
}
)
π¦ Phase 2: Product Catalog
Add Products
db.products.insertMany([
{
name: "MacBook Pro 16-inch",
description: "Powerful laptop with M3 chip, 16GB RAM, 512GB SSD",
category: "Laptops",
price: 2499.99,
stock: 25,
images: ["/images/macbook-1.jpg"],
specifications: {
processor: "Apple M3 Pro",
ram: "16GB",
storage: "512GB SSD"
},
rating: {
average: 4.8,
count: 234
},
tags: ["laptop", "apple", "premium"]
},
{
name: "iPhone 15 Pro",
description: "Latest iPhone with A17 chip and titanium design",
category: "Smartphones",
price: 999.99,
stock: 50,
images: ["/images/iphone-1.jpg"],
specifications: {
processor: "A17 Pro",
storage: "256GB"
},
rating: {
average: 4.7,
count: 567
},
tags: ["smartphone", "apple", "5g"]
}
])
Product Search
// Search for "laptop"
db.products.find(
{ $text: { $search: "laptop" } },
{ score: { $meta: "textScore" } }
).sort({ score: { $meta: "textScore" } })
// Products between $1000 and $2000
db.products.find({
price: { $gte: 1000, $lte: 2000 }
}).sort({ price: 1 })
π Phase 3: Shopping Cart
Add to Cart
var user = db.users.findOne({ email: "john.doe@email.com" })
var product = db.products.findOne({ name: "MacBook Pro 16-inch" })
db.carts.updateOne(
{ userId: user._id },
{
$push: {
items: {
productId: product._id,
productName: product.name,
quantity: 1,
price: product.price,
subtotal: product.price
}
},
$inc: { totalAmount: product.price },
$set: { updatedAt: new Date() }
},
{ upsert: true }
)
View Cart with Product Details
db.carts.aggregate([
{ $match: { userId: user._id } },
{ $unwind: "$items" },
{
$lookup: {
from: "products",
localField: "items.productId",
foreignField: "_id",
as: "productDetails"
}
},
{ $unwind: "$productDetails" },
{
$group: {
_id: "$_id",
items: {
$push: {
productName: "$productDetails.name",
quantity: "$items.quantity",
price: "$items.price",
subtotal: "$items.subtotal"
}
},
totalAmount: { $first: "$totalAmount" }
}
}
])
π Phase 4: Order Processing
Create Order from Cart
var cart = db.carts.findOne({ userId: user._id })
var orderNumber = "ORD-" + new Date().getTime()
var defaultAddress = user.addresses.find(addr => addr.isDefault)
db.orders.insertOne({
orderNumber: orderNumber,
userId: user._id,
items: cart.items,
totalAmount: cart.totalAmount,
status: "pending",
shippingAddress: defaultAddress,
payment: {
method: "credit_card",
status: "pending"
},
createdAt: new Date()
})
// Clear cart
db.carts.updateOne(
{ userId: user._id },
{ $set: { items: [], totalAmount: 0 } }
)
Update Order Status
db.orders.updateOne(
{ orderNumber: orderNumber },
{
$set: {
status: "delivered",
deliveredAt: new Date()
}
}
)
β Phase 5: Reviews & Ratings
Add Product Review
db.reviews.insertOne({
productId: product._id,
userId: user._id,
rating: 5,
title: "Best laptop ever!",
comment: "Amazing performance and battery life",
helpful: 0,
createdAt: new Date()
})
Update Product Rating
var stats = db.reviews.aggregate([
{ $match: { productId: product._id } },
{
$group: {
_id: null,
averageRating: { $avg: "$rating" },
totalReviews: { $sum: 1 }
}
}
]).toArray()[0]
db.products.updateOne(
{ _id: product._id },
{
$set: {
"rating.average": Math.round(stats.averageRating * 10) / 10,
"rating.count": stats.totalReviews
}
}
)
π Phase 6: Analytics & Reporting
Total Revenue
db.orders.aggregate([
{ $match: { status: "delivered" } },
{
$group: {
_id: null,
totalRevenue: { $sum: "$totalAmount" },
totalOrders: { $sum: 1 },
averageOrderValue: { $avg: "$totalAmount" }
}
}
])
Top Selling Products
db.orders.aggregate([
{ $match: { status: { $ne: "cancelled" } } },
{ $unwind: "$items" },
{
$group: {
_id: "$items.productId",
productName: { $first: "$items.productName" },
totalSold: { $sum: "$items.quantity" },
revenue: { $sum: "$items.subtotal" }
}
},
{ $sort: { totalSold: -1 } },
{ $limit: 10 }
])
Customer Lifetime Value
db.orders.aggregate([
{ $match: { status: { $ne: "cancelled" } } },
{
$group: {
_id: "$userId",
totalSpent: { $sum: "$totalAmount" },
orderCount: { $sum: 1 }
}
},
{ $sort: { totalSpent: -1 } },
{ $limit: 10 }
])
β‘ Performance Optimization
- Use compound indexes for common query patterns
- Put $match stages early in aggregation pipelines
- Use projection to limit returned fields
- Monitor slow queries with explain()
- Implement proper connection pooling
db.products.find({
category: "Laptops",
price: { $gte: 1000 }
}).explain("executionStats")
π Advanced Challenges
Challenge 1: Wishlist
Implement wishlist feature where users can save products for later
Challenge 2: Coupon System
Create discount coupons with expiration dates and usage limits
Challenge 3: Recommendations
Build "Customers also bought" using aggregation pipelines
Challenge 4: Flash Sales
Implement time-limited flash sales with atomic operations