Intermediate LevelMongoDB & Mongoose
What is a Covered Query in MongoDB and why does it yield optimal throughput?
❓ Interview Prompt: Explain Covered Queries, totalDocsExamined = 0, satisfying queries entirely from B-Tree index memory, and projection rules.
A Covered Query is a query that is satisfied ENTIRELY by an index without reading underlying collection documents from disk or RAM:
Criteria:
1
All fields in the query filter MUST be part of an index.
2
All fields returned in the projection MUST be part of that SAME index.
3
Explicitly exclude '_id' unless '_id' is part of the index ('_id: 0').
•
Metrics show 'totalDocsExamined: 0', delivering maximum execution speed!
Code Implementation Example
typescript
import { UserModel } from './models/User';
// Assuming compound index exists on { email: 1, name: 1 }
async function getCoveredUserEmail(userEmail: string) {
const result = await UserModel.find(
{ email: userEmail },
{ email: 1, name: 1, _id: 0 } // Project ONLY indexed fields!
).explain('executionStats');
console.log('Docs Examined:', result.executionStats.totalDocsExamined); // 0!
}💡Executing covered queries returning totalDocsExamined: 0.
🎯 Interview Key Takeaway
Covered queries achieve optimal performance by serving data entirely from index memory with totalDocsExamined = 0.
#Covered Query#totalDocsExamined#Index Optimization#Intermediate
Back to all MongoDB & Mongoose Questions→