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

MongoDBと Mastruct の統合

MongoDB をMastraと統合して、 AIエージェントを構築できます。Mastra は、ワークフロー、RAG、evals などの AI アプリケーションを構築するためのプリミティブを提供するオープンソースの TypeScript エージェントフレームワークです。

さらに学ぶには、Mastra のドキュメント または Mastra Github リポジトリ を参照してください。

MongoDBとMastraを使用してAIエージェントを構築できます。MongoDB ベクトル検索と Mastra のエージェントフレームワークを組み合わせることで、エージェントに次の機能を実装できます。

  • MongoDB をベクトルデータベースとして使用するベクトル埋め込みの保存と検索する

  • MongoDBクエリ構文を使用してベクトル検索結果をフィルターする

  • エージェントのツールとして RAG を実装する

  • エージェントのメモリをMongoDBに保存する

Mastra と MongoDB を一緒に使用するには、@mastra/mongodbパッケージをインストールします。

npm install @mastra/mongodb

Mastruct の使用を開始し、プロジェクトを作成する方法については、Mastruct のインストール を参照してください。

MongoDB is a supported database in Mastra. The MongoDBVector class allows you to store and retrieve vector embeddings from MongoDB. You can use this component to implement RAG by storing embeddings from your data and retrieving them using MongoDB Vector Search.

This component requires that you create an MongoDB Vector Search Index.

MastraでMongoDBベクトル保存を使用するには、MongoDBVectorクラスをインポートし、クラスのオブジェクトを作成し、MongoDB接続の詳細を指定します。(例: )。

import { MongoDBVector } from '@mastra/mongodb'
// Instantiate MongoDB as a vector store
const mongoVector = new MongoDBVector({
uri: process.env.MONGODB_URI, // MongoDB connection string
dbName: process.env.MONGODB_DATABASE // Database name
})

このセクションでは、MongoDBをベクトル保存として操作するための最も関連するメソッドについて説明します。メソッドの完全なリストについては、Mastra のドキュメント を参照してください。

埋め込みを検索する前に、コレクションにベクトル検索インデックスを作成する必要があります。dimension パラメーターは、埋め込みモデルに必要な次元数と一致する必要があります。

// Create a vector search index
await mongoVector.createIndex({
indexName: "vector_index", // Name of the index
dimension: 1536, // Must match your embedding model's dimensions
});

MongoDBベクトル保存は、ベクトル検索クエリ結果のメタデータのフィルターをサポートします。

次の例では、フィルター構文を示しています。

// Query with metadata filters
const results = await mongoVector.query({
indexName: "vector_index", // Name of the vector search index
queryVector: queryVector, // Query embedding vector
topK: 10, // Number of results to return
filter: {
category: "electronics", // Simple equality filter
price: { $gt: 100 }, // Numeric comparison
tags: { $in: ["sale", "new"] }, // Array membership
},
});

Tip

For optimal performance, create indexes on metadata fields that you frequently filter on. To learn more, see MongoDB Vector Search Indexes.

詳細については、メタデータ フィルターを参照してください。

Mastruct AIエージェント内のベクトルストアとしてMongoDBを使用してエージェント RAG を実装できます。これにより、エージェントはMongoDB ベクトル Search をタスクを完了するためのツールとして使用できるようになります。

Mastruct は、エージェントが取得にMongoDBを使用する方法を最適化するために、エージェントの指示に含めることができる MONGODB_PROMPT 定数も提供します。詳細については、ベクトル ストアのプロンプトを参照してください。

次の例は、 MongoDB をベクトルストアとして使用して、RAG 機能を持つAIエージェントを作成する方法を示しています。

import { Agent } from '@mastra/core/agent';
import { openai } from '@ai-sdk/openai';
import { MONGODB_PROMPT } from "@mastra/mongodb";
import { createVectorQueryTool } from "@mastra/rag";
// Create a vector query tool for the agent
const vectorQueryTool = createVectorQueryTool({
vectorStoreName: "mongoVector", // Name of MongoDB vector store
indexName: "vector_index", // Name of Vector Search index
model: openai.embedding("text-embedding-3-small"), // Embedding model
});
// Define an AI agent with RAG capabilities
export const ragAgent = new Agent({
name: 'RAG Agent', // Agent name
model: openai('gpt-4o-mini'), // LLM model
instructions: `
Process queries using the provided context. Structure responses to be concise and relevant.
${MONGODB_PROMPT}
`,
tools: { vectorQueryTool }, // Tools available to the agent
});

MongoDB をストレージバックエンドとして持つ Mastruct のメモリ システムで使用できます。これにより、エージェントは過去のインタラクションを記憶し、その情報を使用して将来の決定に通知できます。

完全なチュートリアルについては、MongoDBによるメモリ。を参照してください。

次の例は、 AIエージェントでメモリを使用する方法を示しています。この例では、memoryOptions を使用してリクエストの呼び出しをスコープ設定します。直近性ベースの呼び出しを制限するには、lastMessages: 5 に設定します。semanticRecall を使用して、各一致の周囲のコンテキストに対応するmessageRange: 2 メッセージを含む、最も関連性の高い topK: 3 メッセージを取得します。

import "dotenv/config";
import { mastra } from "./mastra";
const threadId = "123";
const resourceId = "user-456";
const agent = mastra.getAgent("mongodbAgent");
const message = await agent.stream("My name is Mastra", {
memory: {
thread: threadId,
resource: resourceId
}
});
await message.textStream.pipeTo(new WritableStream());
const stream = await agent.stream("What's my name?", {
memory: {
thread: threadId,
resource: resourceId
},
memoryOptions: {
lastMessages: 5,
semanticRecall: {
topK: 3,
messageRange: 2
}
}
});
for await (const chunk of stream.textStream) {
process.stdout.write(chunk);
}

MongoDBで Mastruct を使用する方法の詳細については、以下を参照してください。