QA
Beginner LevelMongoDB & Mongoose

What are MongoDB Single Field and Compound Indexes and why are they necessary?

❓ Interview Prompt: Explain B-Tree indexes, Single Field vs Compound Indexes, Leftmost Prefix Rule, and transforming COLLSCAN into IXSCAN.

Indexes structure collection keys into B-Tree index files. Without indexes, MongoDB must execute a COLLSCAN (full collection scan) reading every document!

Compound Indexes & Leftmost Prefix Rule:

An index on '{ category: 1, price: -1 }' indexes documents first by category ascending, then by price descending.

•
Satisfies queries filtering on '{ category }' OR '{ category, price }'.
•
Does NOT satisfy queries filtering ONLY on '{ price }' (Leftmost Prefix Rule!).

Code Implementation Example

typescript
import { Schema } from 'mongoose';

const orderSchema = new Schema({
  userId: String,
  status: String,
  createdAt: Date
});

// Single field index
orderSchema.index({ userId: 1 });

// Compound index supporting queries on userId + status + createdAt
orderSchema.index({ userId: 1, status: 1, createdAt: -1 });
💡Defining single field and compound B-Tree indexes in Mongoose.
🎯 Interview Key Takeaway

Create compound indexes following the Leftmost Prefix Rule to support multiple query access patterns with a single index.

#Indexes#B-Tree#Compound Index#IXSCAN#Beginner
Back to all MongoDB & Mongoose Questions→

More MongoDB & Mongoose Interview Questions

Beginner LevelMongoDB & Mongoose

How does the MongoDB Aggregation Pipeline work? Explain $match, $group, $lookup, and $project.

Beginner LevelMongoDB & Mongoose

What is MongoDB and how does the BSON document data model work?

Beginner LevelMongoDB & Mongoose

What is the structure of a MongoDB ObjectId and how is it generated?