QA
Intermediate LevelMongoDB & Mongoose

When should you use the hint() method to force index selection?

❓ Interview Prompt: Explain hint(), overriding Query Planner index selection, bypassing bad cached plan evaluations, and risk considerations.

Calling 'hint({ indexName: 1 })' forces the MongoDB Query Planner to use a specific index, bypassing candidate index evaluation:

When to Use:

•
When the query planner selects a sub-optimal index due to stale plan cache metrics.

Code Implementation Example

typescript
import { OrderModel } from './models/Order';

async function forceIndexQuery() {
  // Force query to use specific compound index
  const orders = await OrderModel.find({ status: 'PENDING' })
    .hint({ status: 1, createdAt: -1 })
    .exec();
  return orders;
}
💡Forcing specific index selection using the hint() method.
🎯 Interview Key Takeaway

Use hint() cautiously to override query planner index selection when cached plans perform poorly.

#hint#Query Planner#Indexes#Intermediate
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?