Lab 13: MongoDB Indexes & Queries
Step 1 — Setup: Products Collection
use shopdb
db.products.drop()
db.products.insertMany([
{ name: "Laptop Pro", category: "Electronics", price: 1299.99, stock: 50, tags: ["laptop","portable"], brand: "TechCo", rating: 4.5, createdAt: new Date("2024-01-01") },
{ name: "Wireless Mouse", category: "Electronics", price: 29.99, stock: 200, tags: ["mouse","wireless"], brand: "PeriphCo", rating: 4.2, createdAt: new Date("2024-01-05") },
{ name: "Mechanical Keyboard", category: "Electronics", price: 89.99, stock: 150, tags: ["keyboard","mechanical"], brand: "TypeCo", rating: 4.7, createdAt: new Date("2024-01-10") },
{ name: "Running Shoes", category: "Sports", price: 79.99, stock: 100, tags: ["shoes","running"], brand: "SportCo", rating: 4.3, createdAt: new Date("2024-01-15") },
{ name: "Python Book", category: "Books", price: 39.99, stock: 75, tags: ["python","programming"], brand: "LearnCo", rating: 4.8, createdAt: new Date("2024-01-20") },
{ name: "Coffee Maker", category: "Kitchen", price: 49.99, stock: 80, tags: ["coffee","appliance"], brand: "BrewCo", rating: 3.9, createdAt: new Date("2024-01-25") },
{ name: "Smart Watch", category: "Electronics", price: 299.99, stock: 60, tags: ["watch","smart","wearable"], brand: "TechCo", rating: 4.1, createdAt: new Date("2024-01-30") }
])
print("Total products:", db.products.countDocuments())Step 2 — Single Field Index
Step 3 — Compound Index
Step 4 — Multikey Index (Arrays)
Step 5 — Text Index and Wildcard Index
Step 6 — TTL Index
Step 7 — Covered Queries and hint()
Step 8 — Capstone: Index Strategy for E-Commerce Queries
Summary
Index Type
Created With
Use Case
Last updated
