MongoDB クエリ最適化とインデックスの支援 MongoDB(データベース管理システム)のクエリ最適化とインデックス設定を手助けします。 **次のような場合に使用:** - 「このクエリを最適化するにはどうすればいい?」 - 「どうやってインデックスを作成すればいい?」 - 「このクエリが遅い理由は?」 - 「遅いクエリを直してもらえますか?」 - 「クラスタ(複数のサーバーをつなげたシステム)上の遅いクエリを調べたい」 など、パフォーマンス(処理速度)の改善に関する相談の場合です。 **留意事項:** - MongoDB クエリの基本的な書き方の説明には使用しません。ユーザーがパフォーマンスやインデックス に関する質問をした場合のみ対応します。 - 最適化戦略としてインデックスの活用を優先的に提案します。 - MongoDB MCP が利用可能な場合はそちらを活用します。
Help with MongoDB query optimization and indexing. Use only when the user asks for optimization or performance: "How do I optimize this query?", "How do I index this?", "Why is this query slow?", "Can you fix my slow queries?", "What are the slow queries on my cluster?", etc. Do not invoke for general MongoDB query writing unless user asks for performance or index help. Prefer indexing as optimization strategy. Use MongoDB MCP when available.
次のような場合に使用します:
ユーザーが最適化、遅いクエリ、またはインデックスに関するサポートを明確に求めていない限り、通常のクエリ作成では呼び出さないでください。
ユーザーが遅いクエリを調査したい、または特定のクエリに限らない一般的なパフォーマンス改善を求めている場合:
Atlas MCP サーバーが設定されていない、または正しいクラスタに対して atlas-get-performance-advisor を実行するための十分な情報がない場合は、一般的なパフォーマンス分析には Atlas MCP サーバーの設定と API 認証情報が必要であることをユーザーに伝え、設定を行うか、特定のクエリについて質問するよう提案してください。
ユーザーが特定のクエリについて質問している場合:
その後、収集した情報と MongoDB のベストプラクティス、リファレンスファイルの例に基づいて最適化案を提示します。可能な限り、クエリを完全にカバーするインデックスの作成を優先してください。MongoDB MCP サーバーが使用できない場合でも、最適化案の提示を試みてください。
呼び出し方法。 MongoDB MCP サーバー を呼び出し、正確なツール名 を toolName として、単一の 引数オブジェクト を arguments として渡してください。ツール名をオプション、クエリパラメータ、またはネストされたキーとして渡さず、MCP ツール名として、パラメータを引数オブジェクトとして渡してください。完全な MCP サーバーツールリファレンス: MongoDB MCP Server Tools
データベースツール (MCP クラスタ接続が機能する場合):
| ツール名(正確) | 引数オブジェクト |
|---|---|
collection-indexes |
{ "database": "<db>", "collection": "<coll>" } — 両方とも必須の文字列。 |
explain |
{ "database": "<db>", "collection": "<coll>", "method": [ { "name": "find", "arguments": { "filter": {...}, "sort": {...}, "limit": N } } ], "verbosity": "executionStats" }. method は 1 つのオブジェクトの配列: name は "find"、"aggregate"、または "count"; arguments にはそのメソッドのパラメータを含む (例: find の場合 filter、sort、limit; aggregate の場合 pipeline; count の場合 query)。オプション verbosity: "queryPlanner" (デフォルト)、"executionStats"、"queryPlannerExtended"、"allPlansExecution"。 |
find |
{ "database": "<db>", "collection": "<coll>", "filter": {...}, "projection": {...}, "sort": {...}, "limit": N } — database、collection、filter は必須。オプション: projection、sort、limit。 |
Atlas ツール (Atlas API 認証情報が設定されている場合):
| ツール名(正確) | 引数オブジェクト |
|---|---|
atlas-list-projects |
{} または { "orgId": "<24文字の16進数>" }. パフォーマンスアドバイザー用の projectId を取得するためのプロジェクト ID 付きプロジェクトを返します。 |
atlas-get-performance-advisor |
必須: "projectId" (24 文字の 16 進数文字列)、"clusterName" (文字列、1~64 文字、英数字/アンダースコア/ハイフン)。オプション: "operations" — "suggestedIndexes"、"dropIndexSuggestions"、"slowQueryLogs"、"schemaSuggestions" から選択した文字列の配列 (必要なものだけリクエスト); slowQueryLogs のみ: "since" (ISO 8601 日時)、"namespaces" ("db.coll" 文字列の配列)。 |
ユーザーの質問に対して、最適化しているクエリに関連する接続文字列と Atlas API の両方から情報を取得してください。
典型的なフロー: collection-indexes → explain → find (サンプルドキュメント) を呼び出します。
collection-indexes — 結果の classicIndexes (各行は name、key を含む) を使用して、クエリが既存インデックスを使用できるかどうかを確認。explain — 最初は "queryPlanner" モードで実行して COLLSCAN (全体スキャン) の有無を確認。クエリがインデックスを使用するか、コレクションが非常に小さい場合は、"executionStats" (10秒タイムアウト) で再実行して、スキャンされたドキュメント数と返されたドキュメント数を取得。プロジェクト ID が必要な場合は、最初に atlas-list-projects を呼び出します。その後、必要な operations のみを指定して atlas-get-performance-advisor を呼び出してください:
| 操作値 | 使用する場合 |
|---|---|
slowQueryLogs |
遅いクエリを取得する場合 — 最も遅く、頻繁に実行されるものを優先。オプション: namespaces でコレクションに限定、since で時間枠を指定。 |
suggestedIndexes |
クラスタのインデックス推奨事項を取得する場合 |
dropIndexSuggestions |
ユーザーがインデックスの削除や削減の提案を求めている場合 |
schemaSuggestions |
ユーザーがインデックスと並行してスキーマ設計やクエリ構造のアドバイスを求めている場合 |
MCP ツール名を operations の値として渡さないでください — operations はどのデータを取得するかを示す別の引数です。
ユーザー: 「このクエリが遅いのはなぜですか? db.orders.find({status: 'shipped', region: 'US'}).sort({date: -1})」
MCP DB 接続が設定済みで、データベース名とコレクション名がわかっている場合は、ステップ 1~3 を実行してください。それ以外の場合はステップ 4 に進んでください。
既存のコレクションインデックスを確認:
collection-indexes をデータベース=store、コレクション=orders で呼び出し{_id: 1}、{status: 1}、{date: -1}explain を実行:
explain をメソッド=find、フィルタ={status: 'shipped', region: 'US'}、ソート={date: -1}、詳細度=queryPlanner と executionStats で呼び出し{status: 1} インデックスを使用、メモリ内ソート実行、totalKeysExamined: 50000、nReturned: 100find を実行:
find をリミット=1 で呼び出し、スキーマを推測するためのサンプルドキュメントを取得。MCP Atlas 接続が設定済みの場合は、ステップ 4 を実行してください。それ以外の場合はステップ 5 に進んでください。
atlas-get-performance-advisor を実行:
store、コレクション=orders の遅いクエリログを取得診断: explain 出力と遅いクエリログに基づいて、このクエリは 100 ドキュメントをターゲットとしていますが、50K インデックスエントリをスキャン (選別性: 0.002 と低い)。メモリ内ソートが追加オーバーヘッドを生成。インデックスがフィルタフィールド両方またはソートをサポートしていません。
推奨: ESR ルール(2 つの等価フィールド、その後ソート)に従い、複合インデックス {status: 1, region: 1, date: -1} を作成。これによりメモリ内ソートが排除され、status と region の両方でフィルタリングすることで選別性が向上します。
MongoDB MCP サーバーが設定されていない場合でも、MongoDB のベストプラクティスに従い最適化案を提示してください。
ユーザー: 「クラスタ上の遅いクエリの最適化をサポートしてくれますか?」
atlas-get-performance-advisor を実行:
診断と推奨: 遅いクエリログとパフォーマンスアドバイザーのアドバイスに基づいて、db.orders コレクションに複合インデックス {status: 1, region: 1, date: -1} を作成し、find({status: 'shipped', region: 'US'}).sort({date: -1}) のようなクエリを最適化できます。
パフォーマンスアドバイザーの出力と遅いクエリログを全て検討してください。改善内容と理由を提供し、最大のインパクトが期待できる提案に焦点を当ててください (例: 最も多くのクエリに影響するインデックス、または最悪のパフォーマンスを持つクエリ)。
診断と推奨を開始する前に、リファレンスファイルを読み込んでください。
常に読み込むもの:
references/core-indexing-principles.mdreferences/antipattern-examples.md条件付きで読み込むもの:
references/aggregation-optimization.mdreferences/update-query-examples.md (オペレーションログ効率的な更新と一般的な更新のアンチパターン用)Invoke only when the user wants:
Do not invoke for routine query authoring unless the user has requested help with optimization, slow queries, or indexing.
If the user wants to examine slow queries, or is looking for general performance suggestions (not regarding any particular query):
If Atlas MCP Server for Atlas is not configured or you don’t have enough information to run atlas-get-performance-advisor against the correct cluster, tell the user that general performance analysis requires Atlas MCP Server configuration with API credentials, and suggest they configure it or ask about a specific query instead.
If the user is asking about a particular query:
Then make an optimization suggestion based on collected information and MongoDB best practices and examples from reference files. Prefer creating an index that fully covers the query if possible. If you cannot use MongoDB MCP Server then still try to make a suggestion.
How to invoke. Call the MongoDB MCP server with the exact tool name as toolName and a single arguments object as arguments. Do not pass the tool name as an option, query param, or nested key; pass it as the MCP tool name and the parameters as the arguments object. Full MCP Server tool reference: MongoDB MCP Server Tools.
Database tools (when the MCP cluster connection works):
| Tool name (exact) | Arguments object |
|---|---|
collection-indexes |
{ "database": "<db>", "collection": "<coll>" } — both required strings. |
explain |
{ "database": "<db>", "collection": "<coll>", "method": [ { "name": "find", "arguments": { "filter": {...}, "sort": {...}, "limit": N } } ], "verbosity": "executionStats" }. method is an array of one object: name is "find", "aggregate", or "count"; arguments holds that method's params (e.g. find: filter, sort, limit; aggregate: pipeline; count: query). Optional verbosity: "queryPlanner" (default), "executionStats", "queryPlannerExtended", "allPlansExecution". |
find |
{ "database": "<db>", "collection": "<coll>", "filter": {...}, "projection": {...}, "sort": {...}, "limit": N } — database, collection, and filter are required. Optional: projection, sort, limit. |
Atlas tools (when Atlas API credentials are configured):
| Tool name (exact) | Arguments object |
|---|---|
atlas-list-projects |
{} or { "orgId": "<24-char hex>" }. Returns projects with their IDs; use to get projectId for Performance Advisor. |
atlas-get-performance-advisor |
Required: "projectId" (24-character hex string), "clusterName" (string, 1–64 chars, alphanumeric/underscore/dash). Optional: "operations" — array of strings from "suggestedIndexes", "dropIndexSuggestions", "slowQueryLogs", "schemaSuggestions" (request only what you need); for slowQueryLogs only: "since" (ISO 8601 date-time), "namespaces" (array of "db.coll" strings). |
For a user question, try to fetch information from both the connection string and Atlas API related to the query you are optimizing.
Typical flow: call collection-indexes → explain → find (sample doc).
collection-indexes — Use the result's classicIndexes (each has name, key) to see if the query can already use an existing index.explain — Run in "queryPlanner" mode first to check for COLLSCAN. If the query uses an index or the collection is very small, run again with "executionStats" (10-second timeout) to get docs scanned vs. returned.If you need a project ID, call atlas-list-projects first. Then call atlas-get-performance-advisor with only the operations you need:
| Operation value | Use when |
|---|---|
slowQueryLogs |
Fetching slow queries—prioritize by slowest and most frequent. Optional: namespaces to scope to a collection; since for a time window. |
suggestedIndexes |
Fetching cluster index recommendations |
dropIndexSuggestions |
User asks what to remove or reduce index overhead |
schemaSuggestions |
User asks for schema/query-structure advice alongside indexes |
Do not pass the MCP tool name as an operations value—operations is a separate argument listing what data to fetch.
User: "Why is this query slow? db.orders.find({status: 'shipped', region: 'US'}).sort({date: -1})"
If MCP db connection is configured and the database + collection names are known, run steps 1–3. Otherwise skip to step 4.
Check existing collection indexes:
collection-indexes with database=store, collection=orders{_id: 1}, {status: 1}, {date: -1}Run explain:
explain with method=find, filter={status: 'shipped', region: 'US'}, sort={date: -1}, verbosity=queryPlanner and executionStats{status: 1} index, then in-memory SORT, totalKeysExamined: 50000, nReturned: 100Run find:
find with limit=1 to fetch a sample document to impute the schema.If MCP Atlas connection is configured, run step 4. Otherwise skip to step 5.
Run atlas-get-performance-advisor:
store, collection=orders in the past 24 hoursDiagnose: Based on explain output and slow query logs, this query targets 100 docs but scans 50K index entries (poor selectivity: 0.002). In-memory sort adds overhead. Index doesn't support both filter fields or sort.
Recommend: Create compound index {status: 1, region: 1, date: -1} following ESR (two equality fields, then sort). This eliminates in-memory sort and improves selectivity by filtering on both status and region.
If the MongoDB MCP server is not set up, follow best indexing practices.
User: "Can you help with optimizing slow queries on my cluster?”
{status: 1, region: 1, date: -1} on the db.orders collection to optimize queries such as find({status: 'shipped', region: 'US'}).sort({date: -1})Examine all performance advisor output as well as slow query logs. Provide information on what is being improved and why, and focus on suggestions that have the potential for greatest impact (e.g., indexes that affect the most queries, or queries that have the worst performance).
Before beginning diagnosis and recommendation, load reference files.
Always load:
references/core-indexing-principles.mdreferences/antipattern-examples.mdConditionally load these files:
references/aggregation-optimization.mdreferences/update-query-examples.md for oplog-efficient updates and common update anti-patterns原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。