Master MongoDB indexing and query optimization. Learn index types, explain plans, performance tuning, and query analysis. Use when optimizing slow queries, analyzing performance, or designing indexes.
Analyzes MongoDB queries and creates optimal indexes using explain plans. Use when optimizing slow queries, designing compound indexes, or verifying index usage with ESR rule.
/plugin marketplace add pluginagentmarketplace/custom-plugin-mongodb/plugin install mongodb-developer-plugin@pluginagentmarketplace-mongodbThis skill inherits all available tools. When active, it can use any tool Claude has access to.
assets/config.yamlreferences/GUIDE.mdscripts/helper.pyMaster performance optimization through proper indexing.
// Single field index
await collection.createIndex({ email: 1 });
// Compound index
await collection.createIndex({ status: 1, createdAt: -1 });
// Unique index
await collection.createIndex({ email: 1 }, { unique: true });
// Sparse index (skip null values)
await collection.createIndex({ phone: 1 }, { sparse: true });
// Text index (full-text search)
await collection.createIndex({ title: 'text', description: 'text' });
// TTL index (auto-delete documents)
await collection.createIndex({ createdAt: 1 }, { expireAfterSeconds: 3600 });
// List all indexes
const indexes = await collection.indexes();
console.log(indexes);
// Drop an index
await collection.dropIndex('email_1');
// Drop all non-_id indexes
await collection.dropIndexes();
// Analyze query execution
const explain = await collection.find({ email: 'test@example.com' }).explain('executionStats');
console.log(explain.executionStats);
// Shows: executionStages, nReturned, totalDocsExamined, executionTimeMillis
// Index on one field
db.collection.createIndex({ age: 1 })
// Query uses index if searching on age
db.collection.find({ age: { $gte: 18 } })
// Index on multiple fields - order matters!
db.collection.createIndex({ status: 1, createdAt: -1 })
// Queries that benefit:
// 1. { status: 'active', createdAt: { $gt: date } }
// 2. { status: 'active' }
// But NOT: { createdAt: { $gt: date } } alone
// Automatically created for arrays
db.collection.createIndex({ tags: 1 })
// Matches documents where tags contains value
db.collection.find({ tags: 'mongodb' })
// Full-text search
db.collection.createIndex({ title: 'text', body: 'text' })
// Query
db.collection.find({ $text: { $search: 'mongodb database' } })
// 2D spherical for lat/long
db.collection.createIndex({ location: '2dsphere' })
// Find nearby
db.collection.find({
location: {
$near: { type: 'Point', coordinates: [-73.97, 40.77] },
$maxDistance: 5000
}
})
Equality, Sort, Range
// Query: find active users, sort by created date, limit age
db.users.find({
status: 'active',
age: { $gte: 18 }
}).sort({ createdAt: -1 })
// Optimal index:
db.users.createIndex({
status: 1, // Equality
createdAt: -1, // Sort
age: 1 // Range
})
const explain = await collection.find({ email: 'test@example.com' }).explain('executionStats');
// IXSCAN = Good (index scan)
// COLLSCAN = Bad (collection scan)
console.log(explain.executionStats.executionStages.stage);
// Query results entirely from index
db.users.createIndex({ email: 1, name: 1, _id: 1 })
// This query is "covered" - no need to fetch documents
db.users.find({ email: 'test@example.com' }, { email: 1, name: 1, _id: 0 })
from pymongo import ASCENDING, DESCENDING
# Create index
collection.create_index([('email', ASCENDING)], unique=True)
# Compound index
collection.create_index([('status', ASCENDING), ('createdAt', DESCENDING)])
# Explain plan
explain = collection.find({'email': 'test@example.com'}).explain()
print(explain['executionStats'])
# Drop index
collection.drop_index('email_1')
✅ Index fields used in $match (early in pipeline) ✅ Use ESR rule for compound indexes ✅ Monitor index size and memory ✅ Remove unused indexes ✅ Use explain() to verify index usage ✅ Index strings with high cardinality ✅ Avoid indexing fields with many nulls ✅ Consider index intersection ✅ Regular index maintenance ✅ Monitor query performance
This skill should be used when the user asks to "create a slash command", "add a command", "write a custom command", "define command arguments", "use command frontmatter", "organize commands", "create command with file references", "interactive command", "use AskUserQuestion in command", or needs guidance on slash command structure, YAML frontmatter fields, dynamic arguments, bash execution in commands, user interaction patterns, or command development best practices for Claude Code.
This skill should be used when the user asks to "create an agent", "add an agent", "write a subagent", "agent frontmatter", "when to use description", "agent examples", "agent tools", "agent colors", "autonomous agent", or needs guidance on agent structure, system prompts, triggering conditions, or agent development best practices for Claude Code plugins.
This skill should be used when the user asks to "create a hook", "add a PreToolUse/PostToolUse/Stop hook", "validate tool use", "implement prompt-based hooks", "use ${CLAUDE_PLUGIN_ROOT}", "set up event-driven automation", "block dangerous commands", or mentions hook events (PreToolUse, PostToolUse, Stop, SubagentStop, SessionStart, SessionEnd, UserPromptSubmit, PreCompact, Notification). Provides comprehensive guidance for creating and implementing Claude Code plugin hooks with focus on advanced prompt-based hooks API.