From mongodb-agent-skills
Optimizes MongoDB queries and indexes with strategies for ESR rules, compound/partial/TTL/geospatial/text indexes, aggregation pipelines, and debugging slow ops via explain(), profiler, $indexStats.
npx claudepluginhub romiluz13/mongodb-agent-skillsThis skill uses the workspace's default tool permissions.
Query patterns and indexing strategies for MongoDB, maintained by MongoDB. Contains **46 rules across 5 categories**, prioritized by impact. Includes MongoDB 8.0 features: `bulkWrite` command, `$queryStats` (introduced in MongoDB 6.0.7, with 8.1/8.2 enhancements), Query Settings, and `updateOne` sort option. Indexes are the primary tool for query performance—most slow queries are missing an app...
AGENTS.mdREADME.mdmetadata.jsonrules/_sections.mdrules/_template.mdrules/agg-allowdiskuse.mdrules/agg-avoid-large-unwind.mdrules/agg-graphlookup.mdrules/agg-group-memory-limit.mdrules/agg-lookup-index.mdrules/agg-match-early.mdrules/agg-project-early.mdrules/agg-sort-limit.mdrules/index-clustered.mdrules/index-compound-field-order.mdrules/index-compound-multi-field.mdrules/index-covered-queries.mdrules/index-creation-background.mdrules/index-ensure-usage.mdrules/index-geospatial.mdOptimizes MongoDB queries and suggests indexes using explain plans, collection indexes, and Atlas Performance Advisor for slow query diagnosis and fixes.
Provides MongoDB best practices for schema design patterns, index strategies (ESR rule), aggregation pipelines, connections, and anti-patterns in read-only mode.
Generates read-only MongoDB find queries and aggregation pipelines from natural language, using collection schema, indexes, and sample documents.
Share bugs, ideas, or general feedback.
Query patterns and indexing strategies for MongoDB, maintained by MongoDB. Contains 46 rules across 5 categories, prioritized by impact. Includes MongoDB 8.0 features: bulkWrite command, $queryStats (introduced in MongoDB 6.0.7, with 8.1/8.2 enhancements), Query Settings, and updateOne sort option. Indexes are the primary tool for query performance—most slow queries are missing an appropriate index.
Reference these guidelines when:
$text search with text indexesUse mongodb-search instead when the request is about Atlas Search, $search, $searchMeta, analyzers, synonyms, autocomplete, or search-specific relevance tuning on Atlas-hosted data.
| Priority | Category | Impact | Prefix | Rules |
|---|---|---|---|---|
| 1 | Index Essentials | CRITICAL | index- | 9 |
| 2 | Specialized Indexes | HIGH | index- | 11 |
| 3 | Query Patterns | HIGH | query- | 10 |
| 4 | Aggregation Optimization | HIGH | agg- | 8 |
| 5 | Performance Diagnostics | MEDIUM | perf- | 8 |
index-compound-field-order - Equality first, sort second, range last (ESR rule)index-compound-multi-field - Use compound indexes for multi-field queriesindex-ensure-usage - Avoid COLLSCAN, verify with explain()index-remove-unused - Audit indexes with $indexStatsindex-high-cardinality-first - Put selective fields at index startindex-covered-queries - Include projected fields to avoid document fetchindex-prefix-principle - Compound indexes serve prefix queriesindex-creation-background - Build indexes without blocking operationsindex-size-considerations - Keep indexes in RAM for optimal performanceindex-unique - Enforce uniqueness for identifiers and constraintsindex-partial - Index subset of documents to reduce sizeindex-sparse - Skip documents missing the indexed fieldindex-ttl - Automatic document expiration for sessions/logsindex-text-search - Built-in $text search with stemming and relevanceindex-wildcard - Dynamic field indexing for polymorphic schemasindex-multikey - Array field indexing (one entry per element)index-geospatial - 2dsphere indexes for location queriesindex-hashed - Uniform distribution for equality lookups or shard keysindex-clustered - Ordered storage with clustered collectionsindex-hidden - Safely test index removals in productionquery-use-projection - Fetch only needed fieldsquery-avoid-ne-nin - Use $in instead of negation operatorsquery-or-index - All $or clauses must have indexes for index usagequery-anchored-regex - Start regex with ^ for index usagequery-batch-operations - Avoid N+1 patterns, use $in or $lookupquery-pagination - Use range-based pagination, not skipquery-exists-with-sparse - Understand $exists behavior with sparse indexesquery-sort-collation - Match sort order and collation to indexesquery-bulkwrite-command - MongoDB 8.0 cross-collection atomic batch operationsquery-updateone-sort - MongoDB 8.0 deterministic updates with sort optionagg-match-early - Filter with $match at pipeline startagg-project-early - Reduce document size with $projectagg-sort-limit - Combine $sort with $limit for top-Nagg-lookup-index - Ensure $lookup foreign field is indexedagg-graphlookup - Use $graphLookup for recursive graph traversalagg-avoid-large-unwind - Don't $unwind massive arraysagg-allowdiskuse - Handle large aggregations exceeding 100MBagg-group-memory-limit - Control $group memory and spillsperf-explain-interpretation - Read explain() output like a properf-slow-query-log - Use profiler to find slow operationsperf-index-stats - Find unused indexes with $indexStatsperf-query-plan-cache - Understand and manage query plan cacheperf-use-hint - Force a known-good index when the optimizer errsperf-atlas-performance-advisor - Use Atlas suggestions for missing indexesperf-query-stats - Workload-based query analysis with $queryStats (introduced in MongoDB 6.0.7, with 8.1/8.2 enhancements)perf-query-settings - MongoDB 8.0 persistent index hints with setQuerySettings"If there's no index, it's a collection scan."
Every query without a supporting index scans the entire collection. A 10ms query on 10,000 documents becomes a 10-second query on 10 million documents.
The most important rule for compound index field order:
// Query: status = "active" AND createdAt > lastWeek ORDER BY priority
// ESR: Equality (status) → Sort (priority) → Range (createdAt)
db.tasks.createIndex({ status: 1, priority: 1, createdAt: 1 })
| Position | Type | Example | Why |
|---|---|---|---|
| First | Equality | status: "active" | Narrows to exact matches |
| Second | Sort | ORDER BY priority | Avoids in-memory sort |
| Third | Range | createdAt > date | Scans within sorted data |
ERS Exception: When range predicate is highly selective, placing Range before Sort reduces sort input. Verify with explain().
Read individual rule files for detailed explanations and code examples:
rules/index-compound-field-order.md
rules/perf-explain-interpretation.md
rules/_sections.md
Each rule file contains:
Every rule in this skill provides:
I analyze code patterns, but I can't see your actual database without a connection. This means I might suggest:
Always verify before implementing. Each rule includes verification commands.
For automatic verification, connect the MongoDB MCP Server:
Option 1: Connection String
{
"mcpServers": {
"mongodb": {
"command": "npx",
"args": ["-y", "mongodb-mcp-server", "--readOnly"],
"env": {
"MDB_MCP_CONNECTION_STRING": "mongodb+srv://user:pass@cluster.mongodb.net/mydb"
}
}
}
}
Option 2: Local MongoDB
{
"mcpServers": {
"mongodb": {
"command": "npx",
"args": ["-y", "mongodb-mcp-server", "--readOnly"],
"env": {
"MDB_MCP_CONNECTION_STRING": "mongodb://localhost:27017/mydb"
}
}
}
}
⚠️ Security: Use --readOnly for safety. Remove only if you need write operations.
When connected, I can automatically:
mcp__mongodb__collection-indexesmcp__mongodb__explainmcp__mongodb__aggregateI will NEVER execute write operations without your explicit approval.
| Operation Type | MCP Tools | Action |
|---|---|---|
| Read (Safe) | find, aggregate, explain, collection-indexes, $indexStats | I may run automatically to verify |
| Write (Requires Approval) | create-index, drop-index, update-many, delete-many | I will show the command and wait for your "yes" |
| Destructive (Requires Approval) | drop-collection, drop-database | I will warn you and require explicit confirmation |
When I recommend creating an index or making changes:
Your database, your decision. I'm here to advise, not to act unilaterally.
If you're not sure about a recommendation:
We're a team—let's get this right together.
For the complete guide with all rules expanded: AGENTS.md