All 12 ModulesModule 2 of 12
MongoDB + Query Optimization
Module 2: MongoDB Optimization & Indexing Lab
Migrate device inventory to MongoDB, design compound & partial indexes, write aggregation pipelines, and diagnose slow queries with explain("executionStats").
MongoDBMongooseCompound IndexesPartial IndexesTTL IndexesAggregation Frameworkexplain(executionStats)WiredTiger Engine
Level 1: Build
Level 1: Build — MongoDB Schema & Collections
Implement Mongoose schemas for devices, auditLogs, and backhaulCircuits with strict validation and auto-indexing.
User Story:
As a Senior Backend Engineer, I need to store 500,000 network device telemetry records with lightning-fast querying across environment and status.
Key Deliverables & Specifications:
- Mongoose Schemas for Device, AuditLog, and AutomationJob
- Compound Indexes matching the ESR (Equality, Sort, Range) rule
- Aggregation Pipeline computing device counts grouped by Vendor and Environment
- Automated Seed Script generating 100,000 realistic records for performance profiling
Implementation Roadmap:
1. **Define Schema**: Create `device.schema.ts` with timestamps and enum validation.
2. **Apply Compound Index**: Define `deviceSchema.index({ environment: 1, status: 1, vendor: 1 })`.
3. **Build Aggregation Endpoint**: Implement `GET /api/devices/stats` using `$match`, `$group`, and `$project`.
4. **Implement TTL Index**: Create `auditLogs` collection with a 30-day Time-To-Live expiration index.