对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

将MongoDB与 Mastra 集成

您可以将MongoDB与Mastra集成以构建AI代理。Mastra 是一个开源 TypeScript 代理框架,为构建 AI 应用程序提供基元,包括工作流、RAG 和评估。

要了解更多信息,请参阅 Mastra 文档或 Mastra GitHub 存储库。

您可以将MongoDB与 Mastra 结合使用来构建AI代理。通过将MongoDB 向量搜索与 Mastra 的代理框架相结合,您可以为代理实现以下功能:

  • 使用MongoDB作为矢量数据库来存储和检索向量嵌入

  • 使用MongoDB查询语法过滤器向量搜索结果

  • 将 RAG 作为一种工具在代理中实现

  • 将代理的内存存储在MongoDB中

要将MongoDB与 Mastra 结合使用,请安装 @mastra/mongodb包:

npm install @mastra/mongodb

要开始使用 Mastra 并学习;了解如何创建项目,请参阅安装 Mastra。

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.

此组件要求您创建MongoDB 向量搜索 索引。

要将MongoDB矢量存储与 Mastra 结合使用,请导入 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矢量存储支持对向量搜索查询结果进行元数据过滤器:

  • 不受限制地使用 Mastra 查询语法。

  • 使用标准比较操作符、数组、逻辑操作符和元素操作符

  • 在元数据中使用 mested 字段和数组

  • 根据元数据和原始文档内容进行过滤器

以下用法示例演示了过滤器语法:

// 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
},
});

提示

为获得最佳性能,请为经常过滤的元数据字段创建索引。要了解更多信息,请参阅MongoDB Vector 搜索索引。

要学习;了解更多信息,请参阅元数据筛选器。

您可以将MongoDB用作Mastra AI代理中的向量存储来实现代理 RAG。这允许您的代理使用MongoDB向量搜索作为工具来帮助完成任务。

Mastra 还提供了一个 MONGODB_PROMPT 常量,您可以将其包含在代理指令中,以优化代理使用MongoDB进行检索的方式。要学习;了解更多信息,请参阅向量存储提示。

以下示例展示了如何使用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
});

您可以使用 Mastra 的内存系统, 并以 MongoDB 作为存储后端。这使您的代理能够记住过去的交互,并使用该信息为未来的决策提供信息。

有关完整教程,请参阅 MongoDB 内存。

以下示例演示了如何在AI代理中使用内存。此示例使用 memoryOptions 来确定请求的召回范围。设置 lastMessages: 5 以限制基于新近度的召回。使用 semanticRecall 获取 topK: 3 个最相关的消息,包括每个匹配项上下文的 messageRange: 2 个邻近消息。

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);
}

要学习有关将 Mastra 与 MongoDB 结合使用的更多信息,请参阅: