Lab 13: MongoDB Indexes & Queries

Time: 40 minutes | Level: Practitioner | DB: MongoDB 7

MongoDB indexes work similarly to SQL indexes — they are B-tree (or specialized) structures that speed up queries. Without indexes, every query does a full collection scan (COLLSCAN).


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

📸 Verified Output:

💡 The FETCH stage means MongoDB used an index (IXSCAN) then fetched documents from the collection. COLLSCAN means no index was used — read all documents.


Step 3 — Compound Index

📸 Verified Output:

💡 ESR Rule for compound index column order: Equality fields first, then Sort fields, then Range fields. This matches MongoDB's query execution order.


Step 4 — Multikey Index (Arrays)

📸 Verified Output:

💡 You cannot create a compound index where more than one field is an array. MongoDB cannot index multiple array fields in the same index — would cause a combinatorial explosion.


Step 5 — Text Index and Wildcard Index


Step 6 — TTL Index

📸 Verified Output:


Step 7 — Covered Queries and hint()

💡 A covered query is one where ALL fields needed (in filter AND projection) are in the index. Include _id: 0 in projection to avoid fetching the document just for _id.


Step 8 — Capstone: Index Strategy for E-Commerce Queries


Summary

Index Type
Created With
Use Case

Single field

createIndex({ field: 1 })

Equality, range on one field

Compound

createIndex({ a: 1, b: -1 })

Multi-field queries (ESR order)

Multikey

Auto when field is array

Array containment ($in, $all)

Text

createIndex({ field: "text" })

Full-text $text search

Wildcard

createIndex({ "$**": 1 })

Dynamic/unknown field names

TTL

createIndex + expireAfterSeconds

Auto-expiring documents

Unique

createIndex({ f: 1 }, { unique: true })

Enforce uniqueness

Partial

createIndex({ f: 1 }, { partialFilterExpression: {} })

Subset of documents

Last updated