AI エージェント向け: ドキュメントインデックスは https://www.mongodb.com/ja-jp/docs/llms.txt で利用できます。すべてのページの markdown バージョンは、いずれかの URL パスに .md を追加することで利用できます。
Docs Menu

LangChain JavaScript/Typescript 統合を始めましょう

注意

このチュートリアルでは、Lgachein のJavaScriptライブラリ を使用します。Pythonライブラリを使用するチュートリアルについては、LangChain Pythonを参照してください。

MongoDB ベクトル検索 をLgChuin と統合して、LM アプリケーションを構築し、検索拡張生成 (RAG)(RAG)を実装できます。このチュートリアルでは、Lgachein とMongoDB ベクトル検索 の使用を開始し、データのセマンティック検索を実行し、RG実装を構築する方法を説明します。具体的には、次のアクションを実行します。

  1. 環境を設定します。

  2. カスタム データをMongoDBに保存します。

  3. データにMongoDB ベクトル検索インデックスを作成します。

  4. 次のベクトル検索クエリを実行します。

    • セマンティック検索。

    • メタデータの事前フィルタリングによるセマンティック検索。

    • 最大マージナル関連性(MMR)検索。

  5. MongoDB ベクトル検索を使用してデータの質問に答え、RAG を実装します。

LgChuin は、「チェーン」の使用を通じて LVM アプリケーションの作成を簡素化するオープンソースのフレームワークです。 チェーンは 、RAG を含むさまざまなAIユースケースで組み合わせることができる Lgachein 固有のコンポーネントです。

By integrating MongoDB Vector Search with LangChain, you can use MongoDB as a vector database and use MongoDB Vector Search to implement RAG by retrieving semantically similar documents from your data. To learn more about RAG, see Retrieval-Augmented Generation (RAG) with MongoDB.

Atlas の サンプル データ セット からの映画データを含むコレクションを使用します。

  • 次のいずれかのMongoDBクラスター タイプ

    • An Atlas cluster running MongoDB version 6.0.11, 7.0.2, or later. Ensure that your IP address is included in your Atlas project's access list.

    • A local Atlas deployment created using Python and Docker. Install atlas-local-lib-py (pip install atlas-local-lib-py) to programmatically create and manage local deployments. To learn more, see the atlas-local-lib-py repository.

    • A MongoDB Community cluster with Search and Vector Search installed.

  • A Voyage AI API key. To create an API key, see Manage Voyage AI Model API Keys.

    注意

    Atlas(Atlas UIで作成されたAPIキーの場合)またはVoyage AI(Voyage AIから直接作成されたAPIキーの場合)で支払い方法が設定されていない場合、APIリクエストが失敗する場合があります。

  • OpenAI APIキー。API リクエストに使用できるクレジットがある OpenAI アカウントが必要です。OpenAI のアカウント登録の詳細については、OpenAI API のウェブサイトをご覧ください。

  • Node.js プロジェクトを実行するためのターミナルとコード エディター。

  • npmとNode.jsがインストールされました。

このチュートリアルの環境を設定します。 環境を設定するには、次の手順を実行します。

1

ターミナルで次のコマンドを実行して、 langchain-mongodbという名前の新しいディレクトリを作成し、プロジェクトを初期化します。

mkdir langchain-mongodb
cd langchain-mongodb
npm init -y
2

次のコマンドを実行します:

npm install langchain@latest @langchain/community@latest @langchain/core@latest @langchain/mongodb@latest @langchain/openai@latest @langchain/textsplitters@latest pdf-parse@1 --legacy-peer-deps
3

Configure your project to use ES modules by adding "type": "module" to your package.json file and then saving it.

{
"type": "module",
// other fields...
}
4

プロジェクトで、 get-started.jsという名前のファイルを作成し、次のコードをコピーしてファイルに貼り付けます。 チュートリアル全体でこのファイルにコードを追加します。

この最初のコード スニペットは、このチュートリアルに必要なパッケージをインポートし、環境変数を定義して、 MongoDBクラスターへの接続を確立します。

import { MongoClient } from "mongodb";
import { MongoDBAtlasVectorSearch } from "@langchain/mongodb";
import { ChatOpenAI } from "@langchain/openai";
import { VoyageEmbeddings } from "@langchain/community/embeddings/voyage";
import { PDFLoader } from "@langchain/community/document_loaders/fs/pdf";
import { PromptTemplate } from "@langchain/core/prompts";
import { RecursiveCharacterTextSplitter } from "@langchain/textsplitters";
import { RunnableSequence, RunnablePassthrough } from "@langchain/core/runnables";
import { StringOutputParser } from "@langchain/core/output_parsers";
import * as fs from 'fs';
process.env.VOYAGEAI_API_KEY = "<api-key>"
process.env.OPENAI_API_KEY = "<api-key>";
process.env.MONGODB_URI = "<connection-string>";
const client = new MongoClient(process.env.MONGODB_URI);
const formatDocumentsAsString = (docs) => docs.map(d => d.pageContent).join("\n\n");
5

環境の設定を完了するには、get-started.js<api-key><connection-string> のプレースホルダー値をそれぞれ、Vyage AI APIキー、OpenAI APIキー、MongoDBクラスターの SRV 接続文字列 に置き換えます。接続文字列には、次の形式を使用する必要があります。

mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net

In this section, you define an asynchronous function to load custom data into MongoDB and instantiate your MongoDB cluster as a vector database, also called a vector store. Add the following code into your get-started.js file.

注意

このチュートリアルでは、ベクトルストアのデータソースとして、MongoDB Atlasベストプラクティスというタイトルの一般にアクセス可能な PDFドキュメントを使用します。このドキュメントでは、 MongoDB配置を管理するためのさまざまな推奨事項と主要概念について説明します。

このコードは、次のアクションを実行します。

  • 次のパラメータを指定してMongoDBコレクションを構成します。

    • langchain_db.test ドキュメントを保存するMongoDBコレクションとして 。

    • vector_index ベクトル ストアをクエリするために使用するインデックスとして 。

    • text 未加工のテキスト コンテンツを含むフィールドの名前:

    • embedding ベクトル埋め込みを含むフィールドの名前として。

  • カスタム データを準備するには、次の手順を実行します。

    • 指定された URL から未加工データを検索し、 PDF として保存します。

    • テキストスプリット を使用して、データを小さなドキュメントに分裂。

    • 各ドキュメントの文字数と連続する 2 つのドキュメント間で重複する文字数を決定する チャンク パラメータを指定します。

  • MongoDBAtlasVectorSearch.fromDocumentsメソッドを呼び出して、サンプル ドキュメントからベクトル ストアを作成します。 このメソッドでは、次のパラメーターを指定します。

    • ベクトルデータベースに保存する サンプル ドキュメント 。

    • embeddingフィールドのベクトル埋め込みにテキストを変換するために使用されるモデルとして、AI の埋め込みモデルを使用します。

    • MongoDBクラスターの構成。

async function run() {
try {
// Configure your MongoDB collection
const database = client.db("langchain_db");
const collection = database.collection("test");
const dbConfig = {
collection: collection,
indexName: "vector_index", // The name of the MongoDB Search index to use.
textKey: "text", // Field name for the raw text content. Defaults to "text".
embeddingKey: "embedding", // Field name for the vector embeddings. Defaults to "embedding".
};
// Ensure that the collection is empty
const count = await collection.countDocuments();
if (count > 0) {
await collection.deleteMany({});
}
// Save online PDF as a file
const rawData = await fetch("https://webassets.mongodb.com/MongoDB_Best_Practices_Guide.pdf");
const pdfBuffer = await rawData.arrayBuffer();
const pdfData = Buffer.from(pdfBuffer);
fs.writeFileSync("atlas_best_practices.pdf", pdfData);
// Load and split the sample data
const loader = new PDFLoader(`atlas_best_practices.pdf`);
const data = await loader.load();
const textSplitter = new RecursiveCharacterTextSplitter({
chunkSize: 200,
chunkOverlap: 20,
});
const docs = await textSplitter.splitDocuments(data);
// Instantiate MongoDB as a vector store
const embeddingModel = new VoyageEmbeddings({ modelName: "voyage-4" });
embeddingModel.apiUrl = 'https://ai.mongodb.com/v1/embeddings';
const vectorStore = await MongoDBAtlasVectorSearch.fromDocuments(docs, embeddingModel, dbConfig);
} finally {
// Ensure that the client will close when you finish/error
await client.close();
}
}
run().catch(console.dir);

ファイルを保存し、次のコマンドを実行してデータをMongoDBにロードします。

node get-started.js

ベクトルストアでベクトル検索クエリを有効にするには、langchain_db.testコレクションにMongoDB ベクトル検索インデックスを作成します。

1
  1. Add the following code at the end of the try statement of the asynchronous function that you defined in your get-started.js file. This code creates an index of the vectorSearch type to index the following fields:

    • embedding field as the vector type. The embedding field contains the embeddings created using Voyage AI's voyage-4 embedding model. The index definition specifies 1024 vector dimensions and measures similarity using cosine.

    • loc.pageNumber field as the filter type for pre-filtering data by the page number in the PDF.

    This code also uses an await function to ensure that your search index has synced to your data before it's used.

    1// Ensure index does not already exist, then create your MongoDB Vector Search index
    2const indexes = await collection.listSearchIndexes("vector_index").toArray();
    3if(indexes.length === 0){
    4
    5 // Define your MongoDB Vector Search Index
    6 const index = {
    7 name: "vector_index",
    8 type: "vectorSearch",
    9 definition: {
    10 "fields": [
    11 {
    12 "type": "vector",
    13 "numDimensions": 1024,
    14 "path": "embedding",
    15 "similarity": "cosine"
    16 },
    17 {
    18 "type": "filter",
    19 "path": "loc.pageNumber"
    20 }
    21 ]
    22 }
    23 }
    24
    25 // Run the helper method
    26 const result = await collection.createSearchIndex(index);
    27 console.log(result);
    28}
    29
    30// Wait for index to build and become queryable
    31console.log("Waiting for initial sync...");
    32await new Promise(resolve => setTimeout(() => {
    33 resolve();
    34}, 3000));
  2. ファイルを保存します。

2
node get-started.js

このセクションでは、ベクトル化されたデータに対して実行できるさまざまなクエリを示します。 インデックスが作成できたら、非同期関数に次のコードを追加して、データに対してベクトル検索クエリを実行します。

注意

データをクエリするときに不正確な結果が発生した場合、インデックスの同期に予想以上に時間がかかることがあります。 最初の同期の時間を長くするには、 setTimeout関数の の数を増やします。

1

次のコードでは、 similaritySearchメソッドを使用して、string MongoDB Atlas securityの基本的なセマンティック検索を実行します。 pageContentpageNumberフィールドと フィールドのみを持つドキュメントの関連性順のリストが返されます。

// Basic semantic search
const basicOutput = await vectorStore.similaritySearch(
"MongoDB Atlas security"
);
const basicResults = basicOutput.map((results => ({
pageContent: results.pageContent,
pageNumber: results.metadata.loc.pageNumber,
})))
console.log("Semantic Search Results:")
console.log(basicResults)
if (basicResults.length === 0) {
console.log("No results found after waiting for index sync. Check Atlas Search index status and embedding configuration.");
}
2
node get-started.js
Semantic Search Results:
[
{
pageContent: 'read isolation. \n' +
'With MongoDB Atlas, you can achieve workload isolation with dedicated analytics nodes. Visualization \n' +
'tools like Atlas Charts can be configured to read from analytics nodes only.',
pageNumber: 21
},
{
pageContent: 'well-tuned queries.\n' +
'Built-in slow query profiling is also available if you’re deploying MongoDB with Atlas.',
pageNumber: 16
},
{
pageContent: 'Atlas free tier, or download MongoDB for local \n' +
'development.\n' +
'Review the MongoDB manuals and tutorials in our \n' +
'documentation. \n' +
'More Resources\n' +
'For more on getting started in MongoDB:',
pageNumber: 30
},
{
pageContent: 'If you are running MongoDB on your own infrastructure, you can configure replica set tags to achieve \n' +
'read isolation.',
pageNumber: 21
}
]

You can pre-filter your data by using an MQL match expression that compares the indexed field with another value in your collection. You must index any metadata fields that you want to filter by as the filter type. To learn more, see How to Index Fields for Vector Search.

注意

このチュートリアルのインデックスを作成したときに、 loc.pageNumberフィールドをフィルターとして指定しました。

1

次のコードでは、 similaritySearchメソッドを使用して string MongoDB Atlas securityのセマンティック検索を実行します。 次のパラメータを指定します。

  • 3として返すドキュメントの数。

  • loc.pageNumber演算子を使用して ページのみに表示されるドキュメントを照合する$eq 17フィールドのプレフィルタ。

pageContentpageNumberフィールドと フィールドのみを持つドキュメントの関連性順のリストが返されます。

// Semantic search with metadata filter
const filteredOutput = await vectorStore.similaritySearch("MongoDB Atlas Search", 3, {
preFilter: {
"loc.pageNumber": {"$eq": 22 },
}
});
const filteredResults = filteredOutput.map((results => ({
pageContent: results.pageContent,
pageNumber: results.metadata.loc.pageNumber,
})))
console.log("Semantic Search with Filtering Results:")
console.log(filteredResults)
2
node get-started.js
Semantic Search with Filtering Results:
[
{
pageContent: 'Atlas Search is built for the MongoDB document data model and provides higher performance and',
pageNumber: 22
},
{
pageContent: 'Figure 9: Atlas Search queries are expressed through the MongoDB Query API and backed by the leading search engine library, \n' +
'Apache Lucene.',
pageNumber: 22
},
{
pageContent: 'consider using Atlas Search. The service is built on fully managed Apache Lucene but exposed to users \n' +
'through the MongoDB Aggregation Framework.',
pageNumber: 22
}
]

ダイバーティッドに最適化されたセマンティック関連性の測定値であるMMR(Max MongoDB Atlas)に基づいて、セマンティック検索を実行することもできます。

1

次のコードでは、 maxMarginalRelevanceSearchメソッドを使用して string MongoDB Atlas securityを検索します。 また、次の任意パラメータを定義するオブジェクトも指定します。

  • k 返されたドキュメントの数を3に制限します。

  • fetchK ドキュメントをMDRアルゴリズムに渡す前に、 10ドキュメントのみを取得します。

pageContentpageNumberフィールドと フィールドのみを持つドキュメントの関連性順のリストが返されます。

// Max Marginal Relevance search
const mmrOutput = await vectorStore.maxMarginalRelevanceSearch("MongoDB Atlas security", {
k: 3,
fetchK: 10,
});
const mmrResults = mmrOutput.map((results => ({
pageContent: results.pageContent,
pageNumber: results.metadata.loc.pageNumber,
})))
console.log("Max Marginal Relevance Search Results:")
console.log(mmrResults)
2
node get-started.js
Max Marginal Relevance Search Results:
[
{
pageContent: 'Atlas Search is built for the MongoDB document data model and provides higher performance and',
pageNumber: 22
},
{
pageContent: '• Zoned Sharding — You can define specific rules governing data placement in a sharded cluster.\n' +
'Global Clusters in MongoDB Atlas allows you to quickly implement zoned sharding using a visual UI or',
pageNumber: 27
},
{
pageContent: 'read isolation. \n' +
'With MongoDB Atlas, you can achieve workload isolation with dedicated analytics nodes. Visualization \n' +
'tools like Atlas Charts can be configured to read from analytics nodes only.',
pageNumber: 21
}
]

このセクションでは、 MongoDB ベクトル検索と Lgachein を使用した 2 つの異なる RG 実装を示します。MongoDB ベクトル検索を使用してセマンティックに類似したドキュメントを検索したので、次のコード例を使用して、 MongoDB ベクトル検索によって返されたドキュメントに対して LM に質問に回答するように要求します。

1

このコードでは、次の処理が行われます。

  • MongoDB ベクトル検索 を、セマンティクスで類似したドキュメントを検索するための検索バーとしてインスタンス化します。
  • Defines a LangChain prompt template to instruct the LLM to use these documents as context for your query. LangChain passes these documents to the {context} input variable and your query to the {question} variable.

  • 連鎖 を構築します は、OpenAI のチャット モデルを使用して、プロンプトに基づいてコンテキストを認識する応答を生成します。

  • Atlas のセキュリティ推奨事項に関するサンプル クエリでチェーンをプロンプトします。

  • LLMの応答とコンテキストとして使用されたドキュメントを返します。

// Implement RAG to answer questions on your data
const retriever = vectorStore.asRetriever();
const prompt =
PromptTemplate.fromTemplate(`Answer the question based on the following context:
{context}
Question: {question}`);
const model = new ChatOpenAI({ modelName: "gpt-5-mini" }) // Pick your preferred model. Ensure to enable it in your OpenAI settings dashboard.
const chain = RunnableSequence.from([
{
context: retriever.pipe(formatDocumentsAsString),
question: new RunnablePassthrough(),
},
prompt,
model,
new StringOutputParser(),
]);
// Prompt the LLM
const question = "How can I secure my MongoDB Atlas cluster?";
const answer = await chain.invoke(question);
console.log("Question: " + question);
console.log("Answer: " + answer);
// Return source documents
const retrievedResults = await retriever.invoke(question)
const documents = retrievedResults.map((documents => ({
pageContent: documents.pageContent,
pageNumber: documents.metadata.loc.pageNumber,
})))
console.log("\nSource documents:\n" + JSON.stringify(documents, null, 2))
2

ファイルを保存した後、次のコマンドを実行します。 生成される応答は異なる場合があります。

node get-started.js
Question: How can I secure my MongoDB Atlas cluster?
Answer: You can secure your MongoDB Atlas cluster by achieving workload isolation with dedicated analytics nodes, configuring visualization tools like Atlas Charts to read from analytics nodes only, and using built-in slow query profiling if deploying with Atlas. Additionally, you can distribute replica set members across multiple data centers for added security during election and failover.
Source documents:
[
{
"pageContent": "read isolation. \nWith MongoDB Atlas, you can achieve workload isolation with dedicated analytics nodes. Visualization \ntools like Atlas Charts can be configured to read from analytics nodes only.",
"pageNumber": 21
},
{
"pageContent": "If you are running MongoDB on your own infrastructure, you can configure replica set tags to achieve \nread isolation.",
"pageNumber": 21
},
{
"pageContent": "well-tuned queries.\nBuilt-in slow query profiling is also available if you’re deploying MongoDB with Atlas.",
"pageNumber": 16
},
{
"pageContent": "achieved during election and failover. \nIf possible, distribute replica set members across multiple data centers. If you’re using MongoDB Atlas,",
"pageNumber": 24
}
]
1

このコードでは、次の処理が行われます。

  • MongoDB ベクトル検索 を、セマンティクスで類似したドキュメントを検索するための検索バーとしてインスタンス化します。次の任意パラメーターも指定します。

    • searchTypemmr として、 MongoDB ベクトル検索 が最大マージナル関連性(MMR)に基づいてドキュメントを検索することを指定します。

    • filter をクリックして、 loc.pageNumberフィールドに事前フィルターを追加して、 17ページのみに表示されるドキュメントを含めます。

    • 次のMDR固有のパラメーター。

      • fetchK ドキュメントをMDRアルゴリズムに渡す前に、 20ドキュメントのみを取得します。

      • lambda、結果間の相違の度数を決定するための01の間の値。 0は最大の相違を表し、 1は最小の相違を表します。

  • Defines a LangChain prompt template to instruct the LLM to use these documents as context for your query. LangChain passes these documents to the {context} input variable and your query to the {question} variable.

  • 連鎖 を構築します は、OpenAI のチャット モデルを使用して、プロンプトに基づいてコンテキストを認識する応答を生成します。

  • Atlas のセキュリティ推奨事項に関するサンプル クエリでチェーンをプロンプトします。

  • LLMの応答とコンテキストとして使用されたドキュメントを返します。

// Implement RAG to answer questions on your data
const retriever = await vectorStore.asRetriever({
searchType: "mmr", // Defaults to "similarity"
filter: { preFilter: { "loc.pageNumber": { "$eq": 17 } } },
searchKwargs: {
fetchK: 20,
lambda: 0.1,
},
});
const prompt =
PromptTemplate.fromTemplate(`Answer the question based on the following context:
{context}
Question: {question}`);
const model = new ChatOpenAI({});
const chain = RunnableSequence.from([
{
context: retriever.pipe(formatDocumentsAsString),
question: new RunnablePassthrough(),
},
prompt,
model,
new StringOutputParser(),
]);
// Prompt the LLM
const question = "How can I secure my MongoDB Atlas cluster?";
const answer = await chain.invoke(question);
console.log("Question: " + question);
console.log("Answer: " + answer);
// Return source documents
const retrievedResults = await retriever.invoke(question)
const documents = retrievedResults.map((documents => ({
pageContent: documents.pageContent,
pageNumber: documents.metadata.loc.pageNumber,
})))
console.log("\nSource documents:\n" + JSON.stringify(documents, null, 2))
2

ファイルを保存した後、次のコマンドを実行します。 生成される応答は異なる場合があります。

node get-started.js
Question: How can I secure my MongoDB Atlas cluster?
Answer: One way to secure your MongoDB Atlas cluster is by implementing proper access controls and ensuring that only authorized users have access to your data. You can also enable encryption at rest and in transit, use network security features such as VPC peering, and regularly update and patch your MongoDB database to protect against security vulnerabilities. Additionally, implementing auditing and monitoring tools can help you detect and respond to any security incidents in a timely manner.
Source documents:
[
{
"pageContent": "Optimizing Data \nAccess Patterns\nNative tools in MongoDB for improving query \nperformance and reducing overhead.",
"pageNumber": 17
}
]

MongoDB ベクトル検索 をLgGraph と統合する方法については、 MongoDB をLgGraph.js と統合する を参照してください。

MongoDBは、次の開発者リソースも提供しています。