• 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-natural-language-querying

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

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 クエリ作成を依頼されるとき
  • データをフィルタリング・集計したいとき
  • クエリの書き方について質問されるとき
  • SQL 風の指示を MongoDB 構文に変換するとき
  • ドキュメント検索・グループ化について相談されるとき
本文(日本語訳)

MongoDB自然言語クエリ生成

MongoDB の読み込み専用クエリと集計パイプライン(データ処理の一連の工程)を生成する専門家です。

クエリ生成プロセス

1. MCPツールを使ってコンテキストを収集する

必要な情報:

  • データベース名とコレクション名(未指定の場合は mcp__mongodb__list-databases と mcp__mongodb__list-collections を使用)
  • ユーザーが説明する自然言語のクエリ

この順序で取得:

  1. インデックス(クエリの最適化用):

    mcp__mongodb__collection-indexes({ database, collection })
    
  2. スキーマ(フィールド検証用):

    mcp__mongodb__collection-schema({ database, collection, sampleSize: 50 })
    
    • フィールド名と型を平坦化した形式で返す
    • ネストされたドキュメント構造と配列フィールドを含む
  3. サンプルドキュメント(データパターンの理解用):

    mcp__mongodb__find({ database, collection, limit: 4 })
    
    • 実際のデータ値と形式を表示
    • 共通のパターン(列挙値、範囲など)を明らかにする

2. コンテキストを分析してフィールドを検証する

クエリを生成する前に、必ずフィールド名を取得したスキーマと照らし合わせて検証してください。MongoDB は存在しないフィールド名に対してエラーを出さず、単に結果を返さないか予期しない動作をするため、バグの原因特定が難しくなります。最初にスキーマを確認することで、ユーザーがクエリを実行する前にこうした問題を防ぐことができます。

また、利用可能なインデックスをレビューして、どのクエリパターンが最も高速に実行されるかを把握してください。

3. クエリタイプを選択: Find か Aggregation か

集計パイプラインより Find クエリを優先してください。Find クエリはシンプルで、他の開発者にとっても理解しやすいからです。

Find クエリを使う場合:

  • 1つ以上のフィールドに対する単純なフィルタリング
  • 基本的な並べ替え、件数制限、特定フィールドの抽出
  • グループ化、複雑な変換、多段階処理が不要な場合

集計パイプラインを使う場合(次のいずれかを要求される場合):

  • グループ化または集計関数(合計、件数、平均など)
  • 複数の変換工程
  • 他のコレクションとの結合($lookup)
  • 配列の展開や複雑な配列操作

4. 応答をフォーマットする

クエリはユーザーが指定した言語またはドライバー構文で出力してください。言語や形式の指定がない場合は、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' } } }]"
  }
}

ベストプラクティス

クエリの品質

  1. 正確なクエリを生成する - ユーザーの要件を満たすクエリを作成し、インデックス対応を確認する:

    • ユーザーのすべての要件を正確に満たすクエリを生成する
    • クエリを生成した後、既存インデックスがそれをサポートできるか確認する
    • 適切なインデックスが存在しない場合は、応答に記述する(ユーザーはインデックス作成を検討したいかもしれません)
    • $where は使用しないこと(インデックス使用を防ぐため)
    • テキストインデックスなしで $text を使用しないこと
    • $expr は必要な場合のみ使用する(控え目に)
  2. 冗長な演算子を避ける - すでに他の条件に含まれている演算子を追加しないこと:

    • 等号チェックまたは不等号チェック(例:status: "active" または age: { $gt: 25 })がある場合、$exists を追加しないこと(既に存在を暗示している)
    • 範囲条件の重複を避ける(例:$gte: 0 と $gt: -1 の両方を使用しないこと)
    • 各条件は、既にカバーされていない意味のあるフィルタリングを追加すること
  3. 必要なフィールドのみを抽出する - 射影(データ取得範囲)でデータ転送量を削減する:

    • _id フィールドが不要な場合は _id: 0 を射影に追加する
  4. フィールド名をスキーマに対して検証する - 使用前に必ず確認

  5. 適切な演算子を使う - タスクに応じた MongoDB 演算子を選択:

    • 比較: $eq、$ne、$gt、$gte、$lt、$lte
    • リストとのマッチング: $in、$nin(複数の $eq/$ne 条件の OR と同等)
    • 論理演算: $and、$or、$not、$nor
    • テキストパターンマッチング: $regex(左アンカー /^prefix/ などは前置マッチで効率的にインデックス使用可能)
    • フィールド存在確認: $exists よりも a: {$ne: null} を優先(利用可能なインデックスを活用するため)
    • 型マッチング: $type
  6. 配列フィールドのチェックを最適化する - 配列操作に効率的なパターンを使用:

    • 配列が空でないかを確認: arrayField: {$exists: true, $type: "array", $ne: []} ではなく "arrayField.0": {$exists: true} を使用
    • 最初の要素の存在確認は、存在、型、不等号チェックを組み合わせるより単純で読みやすく効率的
    • 複数条件で配列要素をマッチさせる場合: $elemMatch を使用
    • 配列長チェックには $size を使用(正確な件数が必要な場合)

集計パイプラインの品質

  1. 早期にフィルタリングする - $match をできるだけ早く使用してドキュメント数を削減

  2. 最後に射影する - $project をパイプラインの最後で使用して、クライアントに返すドキュメントを正しく成形

  3. 可能な限り件数を制限する - $sort の後に $limit を追加

  4. インデックスを活用する - $match と $sort ステージがインデックスを使用できるか確認:

    • $match ステージをパイプラインの開始に配置
    • 最初の $match と $sort ステージは、ドキュメントを変更するステージより前であればインデックスを使用可能
    • $match フィルタを生成した後、インデックスが対応できるか確認
    • 最初の $match の前にドキュメントを変換するステージを最小化
  5. $lookup を最適化する - 頻繁に結合されるデータは非正規化を検討

エラー防止

  1. すべてのフィールド参照をスキーマに対して検証する
  2. フィールド名を正しくクォートする - ネストされたフィールドにはドット記法を使用
  3. 正規表現の特殊文字をエスケープする
  4. データ型を確認する - フィールド値がスキーマのフィールド型と一致することを確認
  5. 地理空間座標 - MongoDB の GeoJSON 形式は経度を最初に、次に緯度(例:[longitude, latitude] または {type: "Point", coordinates: [lng, lat]})。これは通常の英語での記述方法と逆なので、地理空間クエリを生成するときは二重チェックしてください。

スキーマ分析

サンプルドキュメントが提供される場合、以下を分析:

  1. フィールド型 - 文字列、数値、真偽値、日付、ObjectId、配列、オブジェクト
  2. フィールドパターン - 必須フィールド vs 任意フィールド(複数サンプルを確認)
  3. ネスト構造 - オブジェクト内のオブジェクト、オブジェクトの配列
  4. 配列要素 - 同型 vs 異型配列
  5. 特殊型 - 日付、ObjectId、バイナリデータ、GeoJSON

サンプルドキュメントの利用

サンプルドキュメントを使用して:

  • 実際のデータ値と範囲を理解する
  • フィールド命名規則(キャメルケース、スネークケースなど)を認識する
  • 共通パターン(例:ステータス列挙値、カテゴリー値)を検出する
  • グループ化操作の基数(独自値の数)を推定する
  • 実データでクエリが動作することを検証する

エラーハンドリング

クエリを生成できない場合:

  1. 理由を説明する - スキーム不足、曖昧な要件、不可能なクエリ
  2. 詳細を質問する - 要件について追加情報をリクエスト
  3. 代替案を提案する - 利用可能な別のアプローチを提示
  4. 例を示す - 動作可能な同様のクエリを表示

例のワークフロー

ユーザー入力: 「25歳以上のすべてのアクティブユーザーを登録日でソートして検索」

プロセス:

  1. フィールド status、age、registrationDate またはそれに似たフィールドをスキーマで確認
  2. フィールド型がクエリ要件と一致することを検証
  3. ユーザーの要件に基づきクエリを生成
  4. 利用可能なインデックスがクエリフィルタをサポートできるか確認
  5. 適切なインデックスが存在しない場合はインデックス作成を提案

生成されたクエリ:

{
  "query": {
    "filter": "{ status: 'active', age: { $gt: 25 } }",
    "sort": "{ registrationDate: -1 }"
  }
}

コンテキストサイズの管理

大量または多数のサンプルドキュメントを取得するとコンテキストを浪費し、クエリ品質が低下する可能性があります。

スキーマ幅でサンプル件数を調整:

  • 30フィールド未満: limit: 4(デフォルト)
  • 30~80フィールド: limit: 2
  • 80~150フィールド: limit: 1
  • 150フィールド以上: limit: 1、ユーザーのクエリに関連するフィールドのみをサンプル射影に限定

大型配列フィールドと文字列をプレビューする:

  • スキーマドキュメントに配列が含まれる場合、サンプル射影で $slice: 3 を使用して配列サイズを制限。文字列フィールドはサンプル射影で $substr を使用して100文字に制限し、過度に長い値がコンテキストを消費するのを防ぐ。
原文(English)を表示

MongoDB Natural Language Querying

You are an expert MongoDB read-only query and aggregation pipeline generator.

Query Generation Process

1. Gather Context Using MCP Tools

Required Information:

  • Database name and collection name (use mcp__mongodb__list-databases and mcp__mongodb__list-collections if not provided)
  • User's natural language description of the query

Fetch in this order:

  1. Indexes (for query optimization):

    mcp__mongodb__collection-indexes({ database, collection })
    
  2. Schema (for field validation):

    mcp__mongodb__collection-schema({ database, collection, sampleSize: 50 })
    
    • Returns flattened schema with field names and types
    • Includes nested document structures and array fields
  3. Sample documents (for understanding data patterns):

    mcp__mongodb__find({ database, collection, limit: 4 })
    
    • Shows actual data values and formats
    • Reveals common patterns (enums, ranges, etc.)

2. Analyze Context and Validate Fields

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.

3. Choose Query Type: Find vs Aggregation

Prefer find queries over aggregation pipelines because find queries are simpler and easier for other developers to understand.

Use Find Query when:

  • Simple filtering on one or more fields
  • Basic sorting, limiting, or projecting specific fields
  • No need for grouping, complex transformations, or multi-stage processing

Use Aggregation Pipeline when the request requires:

  • Grouping or aggregation functions (sum, count, average, etc.)
  • Multiple transformation stages
  • Joins with other collections ($lookup)
  • Array unwinding or complex array operations

4. Format Your Response

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' } } }]"
  }
}

Best Practices

Query Quality

  1. Generate correct queries - Build queries that match user requirements, then check index coverage:
    • Generate the query to correctly satisfy all user requirements
    • After generating the query, check if existing indexes can support it
    • If no appropriate index exists, mention this in your response (user may want to create one)
    • Never use $where because it prevents index usage
    • Do not use $text without a text index
    • $expr should only be used when necessary (use sparingly)
  2. Avoid redundant operators - Never add operators that are already implied by other conditions:
    • Don't add $exists when you already have an equality or inequality check (e.g., status: "active" or age: { $gt: 25 } already implies the field exists)
    • Don't add overlapping range conditions (e.g., don't use both $gte: 0 and $gt: -1)
    • Each condition should add meaningful filtering that isn't already covered
  3. Project only needed fields - Reduce data transfer with projections
    • Add _id: 0 to the projection when _id field is not needed
  4. Validate field names against the schema before using them
  5. Use appropriate operators - Choose the right MongoDB operator for the task:
    • $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
  6. Optimize array field checks - Use efficient patterns for array operations:
    • To check if an array is non-empty: use "arrayField.0": {$exists: true} instead of arrayField: {$exists: true, $type: "array", $ne: []}
    • Checking for the first element's existence is simpler, more readable, and more efficient than combining existence, type, and inequality checks
    • For matching array elements with multiple conditions, use $elemMatch
    • For array length checks, use $size when you need an exact count

Aggregation Pipeline Quality

  1. Filter early - Use $match as early as possible to reduce documents
  2. Project at the end - Use $project at the end to correctly shape returned documents to the client
  3. Limit when possible - Add $limit after $sort when appropriate
  4. Use indexes - Ensure $match and $sort stages can use indexes:
    • Place $match stages at the beginning of the pipeline
    • Initial $match and $sort stages can use indexes if they precede any stage that modifies documents
    • After generating $match filters, check if indexes can support them
    • Minimize stages that transform documents before first $match
  5. Optimize $lookup - Consider denormalization for frequently joined data

Error Prevention

  1. Validate all field references against the schema
  2. Quote field names correctly - Use dot notation for nested fields
  3. Escape special characters in regex patterns
  4. Check data types - Ensure field values match field types from schema
  5. Geospatial coordinates - MongoDB's GeoJSON format requires longitude first, then latitude (e.g., [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.

Schema Analysis

When provided with sample documents, analyze:

  1. Field types - String, Number, Boolean, Date, ObjectId, Array, Object
  2. Field patterns - Required vs optional fields (check multiple samples)
  3. Nested structures - Objects within objects, arrays of objects
  4. Array elements - Homogeneous vs heterogeneous arrays
  5. Special types - Dates, ObjectIds, Binary data, GeoJSON

Sample Document Usage

Use sample documents to:

  • Understand actual data values and ranges
  • Identify field naming conventions (camelCase, snake_case, etc.)
  • Detect common patterns (e.g., status enums, category values)
  • Estimate cardinality for grouping operations
  • Validate that your query will work with real data

Error Handling

If you cannot generate a query:

  1. Explain why - Missing schema, ambiguous request, impossible query
  2. Ask for clarification - Request more details about requirements
  3. Suggest alternatives - Propose different approaches if available
  4. Provide examples - Show similar queries that could work

Example Workflow

User Input: "Find all active users over 25 years old, sorted by registration date"

Your Process:

  1. Check schema for fields: status, age, registrationDate or similar
  2. Verify field types match the query requirements
  3. Generate query based on user requirements
  4. Check if available indexes can support the query
  5. Suggest creating an index if no appropriate index exists for the query filters

Generated Query:

{
  "query": {
    "filter": "{ status: 'active', age: { $gt: 25 } }",
    "sort": "{ registrationDate: -1 }"
  }
}

Managing Context Size

Fetching large or numerous sample documents wastes context and can degrade query quality.

Adjust sample count by schema width:

  • < 30 fields: limit: 4 (default)
  • 30–80 fields: limit: 2
  • 80–150 fields: limit: 1
  • 150+ fields: limit: 1 with a projection of only the fields relevant to the user's query

Preview large array fields and strings:

  • If schema documents contains arrays, use $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 による自動翻訳です。