Docs Menu
Docs Home
/
データベース マニュアル
/

自然言語からMongoDBクエリへ

このページでは、大規模言語モデル(LVM)を使用して自然言語からデータに対するMongoDBクエリを生成する方法に関するガイダンスが提供されます。

mongosh例、Atlas sample_mflixデータベースの で生成されたクエリに対する次の自然言語クエリを考えてみましょう。

次の自然言語クエリがあるとします。

Show me the genres and runtime of
10 movies from 2015 that have
the most comments

これにより、次のmongosh コードが生成されます。

db.movies.aggregate([
{
$match: {
year: 2015,
},
},
{
$sort: {
num_mflix_comments: -1,
},
},
{
$limit: 10,
},
{
$project: {
_id: 0,
genres: 1,
runtime: 1,
},
},
]);

LRM を使用するだけでなく、 MongoDBが構築した次のツールを使用して、自然言語からMongoDBクエリを生成できます。

一般的なタスクで優れたパフォーマンスを発揮するモデルは、通常、 MongoDBクエリ生成でも優れたパフォーマンスを発揮します。 LVM を選択してMongoDBクエリを生成する場合は、 MMLU-Pro Connector Edition などの一般的なベンチマークを参照して、モデル間のパフォーマンスを評価します。

このセクションでは、LVM にMongoDBクエリの生成を求めるための効果的な戦略について説明します。

注意

次のプロンプト戦略は、 MongoDBによって作成されたベンチマークに基づいています。詳しくは、「mongosh Hugeface の自然言語への コードの公開ベンチマーク」を参照してください。

システム プロンプトとも呼ばれるベース プロンプトには、次のようなタスクの概要が明確に表示されている必要があります。

  • 生成するクエリのタイプ。

  • ドライバー言語やクエリを実行するツールなど、予想される出力構造に関する情報。

次の基本プロンプトの例は、 のMongoDB読み取り操作または集計を生成する方法を示しています。mongosh

You are an expert data analyst experienced at using MongoDB.
Your job is to take information about a MongoDB database plus a natural language query and generate a MongoDB shell (mongosh) query to execute to retrieve the information needed to answer the natural language query.
Format the mongosh query in the following structure:
`db.<collection name>.find({/* query */})` or `db.<collection name>.aggregate({/* query */})`

クエリの品質を向上させるには、基本プロンプトに次のガイダンスを追加して、効果的なMongoDBクエリを生成するための一般的なヒントをモデルに提供します。

Some general query-authoring tips:
1. Ensure proper use of MongoDB operators ($eq, $gt, $lt, etc.) and data types (ObjectId, ISODate)
2. For complex queries, use aggregation pipeline with proper stages ($match, $group, $lookup, etc.)
3. Consider performance by utilizing available indexes, avoiding $where and full collection scans, and using covered queries where possible
4. Include sorting (.sort()) and limiting (.limit()), when appropriate, for result set management
5. Handle null values and existence checks explicitly with $exists and $type operators to differentiate between missing fields, null values, and empty arrays
6. Do not include `null` in results objects in aggregation, e.g. do not include _id: null
7. For date operations, NEVER use an empty new date object (e.g. `new Date()`). ALWAYS specify the date, such as `new Date("2024-10-24")`.
8. For Decimal128 operations, prefer range queries over exact equality
9. When querying arrays, use appropriate operators like $elemMatch for complex matching, $all to match multiple elements, or $size for array length checks

応答の品質を向上させるために、応答を生成する前にモデルに「大規模な選択」を要求できます。ソートの連鎖と呼ばれるこの手法はパフォーマンスを向上させますが、生成時間とコストを増加させます。

クエリを生成する前にモデルに段階的に検討させるには、次のテキストを基本プロンプトに追加します。

Think step by step about the code in the answer before providing it. In your thoughts, consider:
1. Which collections are relevant to the query.
2. Which query operation to use (find vs aggregate) and what specific operators ($match, $group, $project, etc.) are needed.
3. What fields are relevant to the query.
4. Which indexes you can use to improve performance.
5. What specific transformations or projections are required.
6. What data types are involved and how to handle them appropriately (ObjectId, Decimal128, Date, etc.).
7. What edge cases to consider (empty results, null values, missing fields).
8. How to handle any array fields that require special operators ($elemMatch, $all, $size).
9. Any other relevant considerations.

クエリの品質を大幅に向上させるには、コレクションからいくつかの サンプルサンプルを含めます。通常、2 から 3 の表すドキュメントは、データ構造に関する十分なコンテキストをモデルに提供します。

サンプルドキュメントを提供する場合は、次のガイドラインに従います。

  • BSON.EJSON.serialize() 関数を使用して、 BSONドキュメントを プロンプト用の EJSON string に変換します。

  • 長いフィールドまたは深くネストされたオブジェクトを切り捨てます。

  • 長い文字列値は除外します。

  • ベクトル埋め込みのような大きな配列の場合、含める要素は数少ない要素のみを含めます。

自然言語からMongoDBクエリを生成する場合、特定のユースケースに次のプロンプト ベストプラクティスを適用します。

LM がよりパフォーマンスの高いクエリを生成するようにするには、プロンプトにコレクションインデックスを含めます。 MongoDBドライバーとmongosh は、インデックス情報を取得するためのメソッドを提供します。例、 Node.jsドライバーは、プロンプトのインデックスを取得するための listIndexes() メソッドを提供します。

ほとんどの LVM ツールには、システム プロンプトに日付が含まれています。ただし、ボックスから LM を使用している場合、モデルは現在の日付や時刻を認識しません。したがって、基本モデルを使用して作業する場合、またはMongoDBツールに独自の自然言語を構築する場合は、プロンプトに最新の日付を含めてください。プログラミング言語の メソッドを使用して、JavaScript の new Date().toString() や Python の str(datetime.now()) などの文字列として現在の日付を取得します。

関連するデータベースコレクションの注釈付きスキーマをプロンプトに含めます。すべての LVM に最適な表現方法はありませんが、一部のアプローチは他のアプローチよりも効果的です。

TypeScript 型、 Python構文モデル、 Go構造体など、データ形状を記述するプログラミング言語ネイティブ型を使用してコレクションを表現することをお勧めします。これらの言語からMongoDBを使用している場合は、データ型 はすでに定義されている可能性があります。 LM をガイドあいまいさを減らすには、各フィールドを説明するためにプロンプトにコメントを追加します。

次の例では、sample_mflix.moviesコレクションの TypeScript 型を示しています。

次の例は、このページで説明されている戦略を使用して、自然言語からmongosh コードを生成する完全なプロンプトを示しています。

次のシステム プロンプトの例を、 MongoDBクエリ生成タスクのテンプレートとして使用します。サンプルプロンプトには、次のコンポーネントが含まれています。

  • タスクの概要と予想される出力形式

  • 一般的なMongoDBクエリ作成ガイダンス

You are an expert data analyst experienced at using MongoDB.
Your job is to take information about a MongoDB database plus a natural language query and generate a MongoDB shell (mongosh) query to execute to retrieve the information needed to answer the natural language query.
Format the mongosh query in the following structure:
`db.<collection name>.find({/* query */})` or `db.<collection name>.aggregate({/* query */})`
Some general query-authoring tips:
1. Ensure proper use of MongoDB operators ($eq, $gt, $lt, etc.) and data types (ObjectId, ISODate).
2. For complex queries, use aggregation pipeline with proper stages ($match, $group, $lookup, etc.).
3. Consider performance by utilizing available indexes, avoiding $where and full collection scans, and using covered queries where possible.
4. Include sorting (.sort()) and limiting (.limit()) when appropriate for result set management.
5. Handle null values and existence checks explicitly with $exists and $type operators to differentiate between missing fields, null values, and empty arrays.
6. Do not include `null` in results objects in aggregation, e.g. do not include _id: null.
7. For date operations, NEVER use an empty new date object (e.g. `new Date()`). ALWAYS specify the date, such as `new Date("2024-10-24")`. Use the provided 'Latest Date' field to inform dates in queries.
8. For Decimal128 operations, prefer range queries over exact equality.
9. When querying arrays, use appropriate operators like $elemMatch for complex matching, $all to match multiple elements, or $size for array length checks.

注意

また、コード生成前に段階的な検討を促します。

次に、次のユーザー メッセージのテンプレートを使用して、データベースと目的のクエリに関する必要なコンテキストをモデルに提供します。

Generate MongoDB Shell (mongosh) queries for the following database and natural language query:
## Database Information
Name: {{Database name}}
Description: {{database description}}
Latest Date: {{latest date}} (use this to inform dates in queries)
### Collections
#### Collection `{{collection name. Do for each collection you want to query over}}`
Description: {{collection description}}
Schema:
```
{{interpreted or annotated schema here}}
```
Example documents:
```
{{truncated example documents here}}
```
Indexes:
```
{{collection index descriptions here}}
```
Natural language query: {{Natural language query here}}

戻る

SQL から MongoDB へ

項目一覧