Lab 12: MongoDB Aggregation Pipeline
Step 1 — Setup: Orders and Customers
use shopdb
db.orders.drop()
db.customers.drop()
db.customers.insertMany([
{ _id: "Alice", email: "[email protected]", tier: "Gold", country: "US" },
{ _id: "Bob", email: "[email protected]", tier: "Silver", country: "UK" },
{ _id: "Carol", email: "[email protected]", tier: "Bronze", country: "US" },
{ _id: "Dave", email: "[email protected]", tier: "Gold", country: "JP" }
])
db.orders.insertMany([
{ customer: "Alice", product: "Laptop Pro", category: "Electronics", amount: 1299.99, qty: 1, date: new Date("2024-01-05") },
{ customer: "Bob", product: "Mouse", category: "Electronics", amount: 29.99, qty: 3, date: new Date("2024-01-10") },
{ customer: "Alice", product: "Python Book", category: "Books", amount: 39.99, qty: 2, date: new Date("2024-01-15") },
{ customer: "Carol", product: "Running Shoes", category: "Sports", amount: 79.99, qty: 1, date: new Date("2024-01-20") },
{ customer: "Bob", product: "Keyboard", category: "Electronics", amount: 89.99, qty: 1, date: new Date("2024-01-22") },
{ customer: "Dave", product: "Laptop Pro", category: "Electronics", amount: 1299.99, qty: 2, date: new Date("2024-01-25") },
{ customer: "Alice", product: "Mouse", category: "Electronics", amount: 29.99, qty: 2, date: new Date("2024-01-28") }
])
print("Orders:", db.orders.countDocuments())Step 2 — $match and $group
Step 3 — $project: Reshape Documents
Step 4 — $lookup: Join Collections
Step 5 — $addFields, $count, $skip, $limit
Step 6 — $facet and $bucket
Step 7 — Pipeline Optimization and explain()
Step 8 — Capstone: Monthly Sales Report with $unwind and $bucket
Summary
Stage
SQL Equivalent
Purpose
Last updated
