• Projects
  • Service
  • About
  • branding.bz
  • Podcast
  • Tips
  • FAQ
  • Recruit
  • Download
  • Contact
  • branding.bz(ブランド構築SaaS)
  • DESIGN NOW(デザインメディア)
  • X
  • LinkedIn
  • Spotify
  • Facebook

213-0011 神奈川県川崎市高津区久本3-6-7-303

© 2026 ID INC. All rights reserved

claude-skills/スキル
SKILLOfficialdatabase

mongodb-query-optimizer

プラグイン
mongodb
ライセンス
Apache-2.0
ソース
GitHub で見る ↗
説明

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.

ユースケース
  • クエリの最適化方法を相談するとき
  • インデックスの作成方法を確認するとき
  • クエリが遅い原因を調べるとき
  • クラスターの遅いクエリを修正するとき
本文(日本語訳)

MongoDB クエリ最適化

このスキルが起動される条件

次のような場合に使用してください:

  • クエリやインデックス(データベースの索引)の最適化やパフォーマンス改善の手助け
  • クエリが遅い理由や高速化の方法についての相談
  • クラスタ上の遅いクエリと、それらの最適化方法

通常のクエリ作成の支援は行いません。ただし、ユーザーが最適化・遅いクエリ・インデックスについての助言を求めた場合は対応します。

全体的なワークフロー

一般的なパフォーマンス改善の相談

ユーザーが遅いクエリを調べたい、または特定のクエリに限らず一般的なパフォーマンス改善のアドバイスを求めている場合:

  • MongoDB MCP サーバーの atlas-get-performance-advisor ツールを使い、遅いクエリのログとパフォーマンスアドバイザーの出力を取得
  • これらの情報に基づいて提案を行う

Atlas MCP サーバーが設定されていないか、正しいクラスタに対して atlas-get-performance-advisor を実行するための情報が不足している場合は、一般的なパフォーマンス分析には Atlas MCP サーバーを API 認証情報付きで設定する必要があることをユーザーに伝え、設定を促すか、代わりに特定のクエリについて尋ねることを提案してください。

特定のクエリに関する相談

ユーザーが特定のクエリについて質問している場合:

  • collection-indexes、explain、find MCP ツールを使い、コレクション(テーブルのような単位)の既存インデックス、そのクエリの explain() 出力、サンプルドキュメント(データ行)を取得
  • atlas-get-performance-advisor MCP ツールを使い、遅いクエリのログとパフォーマンスアドバイザーの出力を取得

収集した情報と MongoDB のベストプラクティス、参考ファイルの例に基づいて最適化の提案を行います。可能な限り、クエリ全体をカバーするインデックスの作成を優先してください。MongoDB MCP サーバーが使えない場合でも、提案を試みてください。

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 進数>" } — プロジェクトと ID を返す。Performance Advisor の projectId を取得するために使用
atlas-get-performance-advisor 必須: "projectId"(24 文字の 16 進数文字列)、"clusterName"(1~64 文字の英数字・アンダースコア・ハイフン)。オプション: "operations" — "suggestedIndexes"、"dropIndexSuggestions"、"slowQueryLogs"、"schemaSuggestions" から選ぶ文字列の配列(必要なものだけリクエスト);slowQueryLogs のみの場合: "since"(ISO 8601 形式の日時)、namespaces("db.coll" 文字列の配列)

ユーザーの質問に対しては、最適化対象のクエリに関連して、接続文字列と Atlas API の両方から情報を取得するように心がけてください。

1. DB 接続文字列が MongoDB MCP で動作する場合

典型的なフロー: collection-indexes → explain → find(サンプルドキュメント)

  • collection-indexes — 結果の classicIndexes(各要素は name、key を持つ)を使い、既存インデックスがそのクエリで使えるかどうかを確認
  • explain — まず "queryPlanner" モードで実行し、COLLSCAN(全件スキャン)がないかチェック。クエリがインデックスを使用しているか、コレクションが非常に小さい場合は、"executionStats"(タイムアウト 10 秒)で再実行し、スキャンされたドキュメント数と返されたドキュメント数を確認

2. Atlas API アクセスが MongoDB MCP で機能する場合

プロジェクト ID が必要な場合は、まず atlas-list-projects を呼び出してください。次に、必要な operations だけを指定して atlas-get-performance-advisor を呼び出します:

操作の値 使用する場面
slowQueryLogs 遅いクエリを取得する場合 — 最も遅く、最も頻繁に実行されるものを優先。オプション: namespaces で特定のコレクションに限定;since で期間を指定
suggestedIndexes クラスタのインデックス推奨事項を取得する場合
dropIndexSuggestions ユーザーが不要なインデックスや削除すべきインデックスについて尋ねる場合
schemaSuggestions ユーザーがスキーマ・クエリ構造についてインデックスと一緒にアドバイスを求める場合

MCP ツール名を operations の値として渡さないでください — operations は取得すべきデータを列挙する別個の引数です。

ワークフロー例 1(特定のクエリに関する相談)

ユーザー: 「このクエリが遅いのはなぜですか?db.orders.find({status: 'shipped', region: 'US'}).sort({date: -1})」

MCP DB 接続が設定されており、データベース名とコレクション名がわかっている場合は、ステップ 1~3 を実行してください。そうでない場合はステップ 4 にスキップしてください。

  1. 既存コレクションのインデックスを確認:

    • collection-indexes を database=store、collection=orders で呼び出し
    • 結果: {_id: 1}、{status: 1}、{date: -1} が存在
  2. explain を実行:

    • explain を method=find、filter={status: 'shipped', region: 'US'}、sort={date: -1}、verbosity=queryPlanner と executionStats で呼び出し
    • 結果: {status: 1} インデックスを使用、その後メモリ内で並べ替え、totalKeysExamined: 50000、nReturned: 100
  3. find を実行:

    • find を limit=1 で呼び出し、スキーマを推測するためのサンプルドキュメントを取得

MCP Atlas 接続が設定されている場合は、ステップ 4 を実行してください。そうでない場合はステップ 5 にスキップしてください。

  1. atlas-get-performance-advisor を実行:

    • MCP 接続文字列からクラスタ名を取得するか、ユーザーに projectId/clusterName を尋ねる
    • slowQueryLogs を使い、過去 24 時間の database=store、collection=orders からの遅いクエリログを取得
    • suggestedIndexes を使い、このクエリのインデックス提案をチェック
  2. 診断: explain 出力とスローログに基づき、このクエリは 100 ドキュメント(レコード)を対象としていますが、50,000 のインデックスエントリをスキャンしています(選別性が低い: 0.002)。メモリ内の並べ替えがオーバーヘッドを追加しています。インデックスはフィルタ条件両方または並べ替え条件をサポートしていません。

  3. 推奨: ESR ルール(等値条件 2 つ、次に並べ替え)に従い、複合インデックス {status: 1, region: 1, date: -1} を作成してください。これでメモリ内の並べ替えが不要になり、status と region の両方でフィルタリングすることで選別性が向上します。

MongoDB MCP サーバーが設定されていない場合でも、MongoDB のベストプラクティスに従って提案を行ってください。

ワークフロー例 2(一般的なデータベースパフォーマンス改善の相談)

ユーザー: 「クラスタの遅いクエリ最適化を手伝ってもらえますか?」

  1. atlas-get-performance-advisor を実行:

    • 接続文字列からクラスタ名を取得し、atlas-list-projects で必要なプロジェクト名を推測します。確実でない場合はユーザーにクラスタ名とプロジェクト ID を尋ねる
    • slowQueryLogs を使い、過去 24 時間の遅いクエリログを取得
    • suggestedIndexes を使用
    • dropIndexSuggestions を使用
    • schemaSuggestions を使用
  2. 診断と推奨: スローログとパフォーマンスアドバイザーの提案に基づき、db.orders コレクションに複合インデックス {status: 1, region: 1, date: -1} を作成し、find({status: 'shipped', region: 'US'}).sort({date: -1}) のようなクエリを最適化できます

パフォーマンスアドバイザーの出力とスローログをすべて調査してください。何が改善され、なぜそうなるのかについて情報を提供し、最大のインパクトが期待できる提案に焦点を当ててください(例:多くのクエリに影響するインデックス、最も悪いパフォーマンスのクエリなど)。

参考ファイルの読み込み

診断と推奨を開始する前に、参考ファイルを読み込んでください。

常に読み込む:

  • references/core-indexing-principles.md
  • references/antipattern-examples.md

条件に基づいて読み込む:

  • 集約パイプラインを診断する場合 → references/aggregation-optimization.md
  • replaceOne、findOneAndUpdate など、ドキュメントを変更するクエリを診断する場合 → references/update-query-examples.md(オペレーションログ効率的な更新と一般的な更新のアンチパターン)

出力

  • 回答は簡潔明瞭に: インデックスと最適化提案について数文で、その理由を含める(例:一般的なインデックス原則、クラスタの遅いクエリログの観察、パフォーマンスアドバイザーの提案の確認)
  • 最大インパクトのあるインデックスまたは最適化に焦点を当ててください — 省略した最適化がある場合はユーザーに知らせ、質問されれば提示してください
  • 「これらのインデックスを作成すれば、アプリケーションのパフォーマンスが確実に向上します」のような強い表現は避けてください — これらは特定のクエリに対する提案であることを説明し、その理由を述べてください
  • 既存インデックス数を考慮してください(わかっている場合) — 一般的に 1 つのコレクションには 20 個以上のインデックスがあるべきではありません
  • インデックスの削除は Atlas パフォーマンスアドバイザーの提案がある場合のみ
原文(English)を表示

MongoDB Query Optimizer

When this skill is invoked

Invoke only when the user wants:

  • Query/index optimization or performance help
  • Why a query is slow or how to speed it up
  • Slow queries on their cluster and/or how to optimize them

Do not invoke for routine query authoring unless the user has requested help with optimization, slow queries, or indexing.

High Level Workflow

General Performance Help

If the user wants to examine slow queries, or is looking for general performance suggestions (not regarding any particular query):

  • Use MongoDB MCP server atlas-get-performance-advisor tool to fetch slow query logs and performance advisor output
  • Make suggestions based on this information

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.

Help with a Specific Query

If the user is asking about a particular query:

  • Use collection-indexes, explain, and find MCP tools to get existing indexes on the collection, explain() output for the query, and a sample document from the collection
  • Use atlas-get-performance-advisor MCP tool to fetch slow query logs and performance advisor output

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.

MCP: available tools

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.

1. DB connection string works for MongoDB MCP

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.

2. Atlas API access works for MongoDB MCP

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.

Example workflow 1 (help with specific query)

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.

  1. Check existing collection indexes:

    • Call collection-indexes with database=store, collection=orders
    • Result shows: {_id: 1}, {status: 1}, {date: -1}
  2. Run explain:

    • Call explain with method=find, filter={status: 'shipped', region: 'US'}, sort={date: -1}, verbosity=queryPlanner and executionStats
    • Result: Uses {status: 1} index, then in-memory SORT, totalKeysExamined: 50000, nReturned: 100
  3. Run find:

    • Call 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.

  1. Run atlas-get-performance-advisor:

    • Try to get the cluster name from the MCP connection string, or ask the user for projectId/clusterName
    • Use slowQueryLogs to fetch slow query logs from database=store, collection=orders in the past 24 hours
    • Use suggestedIndexes to check for index suggestions for the query
  2. Diagnose: 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.

  3. 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.

Example workflow 2 (general database performance help)

User: "Can you help with optimizing slow queries on my cluster?”

  1. Run atlas-get-performance-advisor:
    • Try to get the cluster name from the connection string and deduce the project name you need in atlas-list-projects; if you are not sure, then ask the user for cluster name and project id.
    • Use slowQueryLogs to fetch slow query logs from the past 24 hours
    • Use suggestedIndexes
    • Use dropIndexSuggestions
    • Use schemaSuggestions
  2. Diagnose and Recommend: Based on slow query logs and performance advisor advice, you can create the compound index {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).

Load references

Before beginning diagnosis and recommendation, load reference files.

Always load:

  • references/core-indexing-principles.md
  • references/antipattern-examples.md

Conditionally load these files:

  • If diagnosing aggregation pipelines → references/aggregation-optimization.md
  • If diagnosing queries that change docs such as replaceOne, findOneAndUpdate, etc. → references/update-query-examples.md for oplog-efficient updates and common update anti-patterns

Output

  • Keep answers short and clear: a few sentences on index and optimization suggestions, and reasoning behind them (e.g. general indexing principles, observing slow query logs in the cluster, or seeing advice in Performance Advisor)
  • Focus on highest impact indexes or optimizations - if you've omitted some optimizations let the user know and present them if asked.
  • Do not use strong language, such as saying “You should create these indexes and they will definitely improve application performance” - Explain they are suggestions for certain queries, and give the reasoning behind them.
  • Consider how many indexes already exist on the collection (if known) - there shouldn’t generally be more than 20
  • Suggest removing indexes only if the suggestion comes from Atlas Performance Advisor
  • Do not create indexes directly via MCP unless the user gives approval

原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。