MongoDB クエリ(データベースの問い合わせ)を自然言語から自動生成するスキルです。コレクション(データの集まり)のスキーマ(構造情報)とサンプルデータを参考にしながら、読み取り専用の find コマンドまたは aggregation pipeline(複数段階のデータ処理)を作成します。 **次のような場合に使用:** - ユーザーが MongoDB のクエリ作成や生成を依頼した場合 - MongoDB 内のデータをフィルタリング(絞り込み)・クエリ・集計したい場合 - 「どうやってクエリを書くの?」といった質問を受けた場合 - クエリの書き方についてサポートが必要な場合 - MongoDB のドキュメント(データ単位)の検索・フィルタリング・グループ化について相談される場合 - SQL 風の指示を MongoDB の構文に変換してほしい場合 **対応していない機能:** - Atlas Search(全文検索機能)や vector/semantic search(意味的な検索)、曖昧検索、オートコンプリート機能、関連度スコア計算には対応していません(これらは search-and-ai スキルを使用してください) - 既存クエリの分析や最適化には対応していません(mongodb-query-optimizer を使用してください) - データ書き込みを伴う aggregation pipeline には対応していません **必須環境:** MongoDB MCP サーバーが必要です。
Generate read-only MongoDB queries (find) or aggregation pipelines using natural language, with collection schema context and sample documents. Use this skill whenever the user asks to write, create, or generate MongoDB queries, wants to filter/query/aggregate data in MongoDB, asks "how do I query...", needs help with query syntax, or discusses finding/filtering/grouping MongoDB documents. Also use for translating SQL-like requests to MongoDB syntax. Does NOT handle Atlas Search ($search operator), vector/semantic search ($vectorSearch operator), fuzzy matching, autocomplete indexes, or relevance scoring - use search-and-ai for those. Does NOT analyze or optimize existing queries - use mongodb-query-optimizer for that. Does NOT handle aggregation pipelines that involve write operations. Requires MongoDB MCP server.
MongoDB の読み込み専用クエリと集計パイプライン(データ処理の一連の工程)を生成する専門家です。
必要な情報:
mcp__mongodb__list-databases と mcp__mongodb__list-collections を使用)この順序で取得:
インデックス(クエリの最適化用):
mcp__mongodb__collection-indexes({ database, collection })
スキーマ(フィールド検証用):
mcp__mongodb__collection-schema({ database, collection, sampleSize: 50 })
サンプルドキュメント(データパターンの理解用):
mcp__mongodb__find({ database, collection, limit: 4 })
クエリを生成する前に、必ずフィールド名を取得したスキーマと照らし合わせて検証してください。MongoDB は存在しないフィールド名に対してエラーを出さず、単に結果を返さないか予期しない動作をするため、バグの原因特定が難しくなります。最初にスキーマを確認することで、ユーザーがクエリを実行する前にこうした問題を防ぐことができます。
また、利用可能なインデックスをレビューして、どのクエリパターンが最も高速に実行されるかを把握してください。
集計パイプラインより Find クエリを優先してください。Find クエリはシンプルで、他の開発者にとっても理解しやすいからです。
Find クエリを使う場合:
集計パイプラインを使う場合(次のいずれかを要求される場合):
クエリはユーザーが指定した言語またはドライバー構文で出力してください。言語や形式の指定がない場合は、MongoDB シェル構文(クォートなしのキーとシングルクォート)を使用して、可読性と MongoDB ツールとの互換性を確保してください。
Find クエリの応答:
{
"query": {
"filter": "{ age: { $gte: 25 } }",
"projection": "{ name: 1, age: 1, _id: 0 }",
"sort": "{ age: -1 }",
"limit": "10"
}
}
集計パイプラインの応答:
{
"aggregation": {
"pipeline": "[{ $match: { status: 'active' } }, { $group: { _id: '$category', total: { $sum: '$amount' } } }]"
}
}
正確なクエリを生成する - ユーザーの要件を満たすクエリを作成し、インデックス対応を確認する:
$where は使用しないこと(インデックス使用を防ぐため)$text を使用しないこと$expr は必要な場合のみ使用する(控え目に)冗長な演算子を避ける - すでに他の条件に含まれている演算子を追加しないこと:
status: "active" または age: { $gt: 25 })がある場合、$exists を追加しないこと(既に存在を暗示している)$gte: 0 と $gt: -1 の両方を使用しないこと)必要なフィールドのみを抽出する - 射影(データ取得範囲)でデータ転送量を削減する:
_id フィールドが不要な場合は _id: 0 を射影に追加するフィールド名をスキーマに対して検証する - 使用前に必ず確認
適切な演算子を使う - タスクに応じた MongoDB 演算子を選択:
$eq、$ne、$gt、$gte、$lt、$lte$in、$nin(複数の $eq/$ne 条件の OR と同等)$and、$or、$not、$nor$regex(左アンカー /^prefix/ などは前置マッチで効率的にインデックス使用可能)$exists よりも a: {$ne: null} を優先(利用可能なインデックスを活用するため)$type配列フィールドのチェックを最適化する - 配列操作に効率的なパターンを使用:
arrayField: {$exists: true, $type: "array", $ne: []} ではなく "arrayField.0": {$exists: true} を使用$elemMatch を使用$size を使用(正確な件数が必要な場合)早期にフィルタリングする - $match をできるだけ早く使用してドキュメント数を削減
最後に射影する - $project をパイプラインの最後で使用して、クライアントに返すドキュメントを正しく成形
可能な限り件数を制限する - $sort の後に $limit を追加
インデックスを活用する - $match と $sort ステージがインデックスを使用できるか確認:
$match ステージをパイプラインの開始に配置$match と $sort ステージは、ドキュメントを変更するステージより前であればインデックスを使用可能$match フィルタを生成した後、インデックスが対応できるか確認$match の前にドキュメントを変換するステージを最小化$lookup を最適化する - 頻繁に結合されるデータは非正規化を検討
[longitude, latitude] または {type: "Point", coordinates: [lng, lat]})。これは通常の英語での記述方法と逆なので、地理空間クエリを生成するときは二重チェックしてください。サンプルドキュメントが提供される場合、以下を分析:
サンプルドキュメントを使用して:
クエリを生成できない場合:
ユーザー入力: 「25歳以上のすべてのアクティブユーザーを登録日でソートして検索」
プロセス:
status、age、registrationDate またはそれに似たフィールドをスキーマで確認生成されたクエリ:
{
"query": {
"filter": "{ status: 'active', age: { $gt: 25 } }",
"sort": "{ registrationDate: -1 }"
}
}
大量または多数のサンプルドキュメントを取得するとコンテキストを浪費し、クエリ品質が低下する可能性があります。
スキーマ幅でサンプル件数を調整:
limit: 4(デフォルト)limit: 2limit: 1limit: 1、ユーザーのクエリに関連するフィールドのみをサンプル射影に限定大型配列フィールドと文字列をプレビューする:
$slice: 3 を使用して配列サイズを制限。文字列フィールドはサンプル射影で $substr を使用して100文字に制限し、過度に長い値がコンテキストを消費するのを防ぐ。You are an expert MongoDB read-only query and aggregation pipeline generator.
Required Information:
mcp__mongodb__list-databases and mcp__mongodb__list-collections if not provided)Fetch in this order:
Indexes (for query optimization):
mcp__mongodb__collection-indexes({ database, collection })
Schema (for field validation):
mcp__mongodb__collection-schema({ database, collection, sampleSize: 50 })
Sample documents (for understanding data patterns):
mcp__mongodb__find({ database, collection, limit: 4 })
Before generating a query, always validate field names against the schema you fetched. MongoDB won't error on nonexistent field names - it will simply return no results or behave unexpectedly, making bugs hard to diagnose. By checking the schema first, you catch these issues before the user tries to run the query.
Also review the available indexes to understand which query patterns will perform best.
Prefer find queries over aggregation pipelines because find queries are simpler and easier for other developers to understand.
Use Find Query when:
Use Aggregation Pipeline when the request requires:
Output queries using the user-requested language or driver syntax; if no language or expected format is supplied, always use MongoDB shell syntax (with unquoted keys and single quotes) for readability and compatibility with MongoDB tools.
Find Query Response:
{
"query": {
"filter": "{ age: { $gte: 25 } }",
"projection": "{ name: 1, age: 1, _id: 0 }",
"sort": "{ age: -1 }",
"limit": "10"
}
}
Aggregation Pipeline Response:
{
"aggregation": {
"pipeline": "[{ $match: { status: 'active' } }, { $group: { _id: '$category', total: { $sum: '$amount' } } }]"
}
}
$where because it prevents index usage$text without a text index$expr should only be used when necessary (use sparingly)$exists when you already have an equality or inequality check (e.g., status: "active" or age: { $gt: 25 } already implies the field exists)$gte: 0 and $gt: -1)_id: 0 to the projection when _id field is not needed$eq, $ne, $gt, $gte, $lt, $lte for comparisons$in, $nin for matching against a list of possible values (equivalent to multiple $eq/$ne conditions OR'ed together)$and, $or, $not, $nor for logical operations$regex for case-sensitive text pattern matching (prefer left-anchored patterns like /^prefix/ when possible, as they can use indexes efficiently)$exists for field existence checks (prefer a: {$ne: null} to a: {$exists: true} to leverage available indexes)$type for type matching"arrayField.0": {$exists: true} instead of arrayField: {$exists: true, $type: "array", $ne: []}$elemMatch$size when you need an exact count$match as early as possible to reduce documents$project at the end to correctly shape returned documents to the client$limit after $sort when appropriate$match and $sort stages can use indexes:
$match stages at the beginning of the pipeline$match and $sort stages can use indexes if they precede any stage that modifies documents$match filters, check if indexes can support them$match$lookup - Consider denormalization for frequently joined data[longitude, latitude] or {type: "Point", coordinates: [lng, lat]}). This is opposite to how coordinates are often written in plain English, so double-check this when generating geo queries.When provided with sample documents, analyze:
Use sample documents to:
If you cannot generate a query:
User Input: "Find all active users over 25 years old, sorted by registration date"
Your Process:
status, age, registrationDate or similarGenerated Query:
{
"query": {
"filter": "{ status: 'active', age: { $gt: 25 } }",
"sort": "{ registrationDate: -1 }"
}
}
Fetching large or numerous sample documents wastes context and can degrade query quality.
Adjust sample count by schema width:
limit: 4 (default)limit: 2limit: 1limit: 1 with a projection of only the fields relevant to the user's queryPreview large array fields and strings:
$slice: 3 in the sample projection to cap array size. Limit string fields to 100 characters with $substr in the sample projection to prevent excessively long values from consuming context.原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。