> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # MongoDB 存储 MongoDB 存储实现使用 MongoDB 数据库提供高容量存储解决方案,同时支持文档存储和向量操作。 ## 安装 **npm**: ```bash npm install @mastra/mongodb@latest ``` **pnpm**: ```bash pnpm add @mastra/mongodb@latest ``` **Yarn**: ```bash yarn add @mastra/mongodb@latest ``` **Bun**: ```bash bun add @mastra/mongodb@latest ``` ## 使用方法 请确保你拥有已启用 Atlas Search 的 [MongoDB Atlas Local(通过 Docker)](https://www.mongodb.com/docs/atlas/cli/current/atlas-cli-deploy-docker/) 或 [MongoDB Atlas Cloud](https://www.mongodb.com/docs/atlas/cli/current/atlas-cli-getting-started/) 实例。建议使用 MongoDB 7.0+。 ```typescript import { MongoDBStore } from '@mastra/mongodb' const storage = new MongoDBStore({ id: 'mongodb-storage', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DB_NAME, }) ``` ## 参数 **id** (`string`): 此 storage 实例的唯一标识符。 **uri** (`string`): MongoDB 连接字符串(例如 mongodb+srv://user:password\@cluster.mongodb.net)。 **url** (`string`): 已弃用。请改用 uri。MongoDB 连接字符串(为向后兼容而支持)。 **dbName** (`string`): storage 要使用的数据库名称。 **options** (`MongoClientOptions`): 用于高级配置的 MongoDB client 选项(SSL、连接池等)。请参阅连接选项。 **disableInit** (`boolean`): 为 true 时,将禁用自动初始化(创建 collection)。适用于需要显式运行 migration 的 CI/CD pipeline。此值为 true 时,你必须手动调用 storage.init()。 **skipDefaultIndexes** (`boolean`): 为 true 时,初始化期间不会创建默认 index。适用于单独管理 index 或仅使用自定义 index 的情况。 **indexes** (`MongoDBIndexConfig[]`): 初始化期间要创建的自定义 index。每个 index 必须指定 collection、keys 和可选的 index 选项。请参阅index。 **connectorHandler** (`ConnectorHandler`): 用于高级连接管理的自定义连接处理程序。可替代直接提供 uri/dbName。 > **弃用通知:** `url` 参数已弃用,但仍为向后兼容而受支持。请在所有新代码中改用 `uri`。 ## 构造函数示例 你可以通过以下方式实例化 `MongoDBStore`: ```ts import { MongoDBStore } from '@mastra/mongodb' // Basic connection without custom options const store1 = new MongoDBStore({ id: 'mongodb-storage-01', uri: 'mongodb+srv://user:password@cluster.mongodb.net', dbName: 'mastra_storage', }) // Using connection string with options const store2 = new MongoDBStore({ id: 'mongodb-storage-02', uri: 'mongodb+srv://user:password@cluster.mongodb.net', dbName: 'mastra_storage', options: { retryWrites: true, maxPoolSize: 10, serverSelectionTimeoutMS: 5000, socketTimeoutMS: 45000, }, }) // With custom indexes const store3 = new MongoDBStore({ id: 'mongodb-storage-03', uri: 'mongodb+srv://user:password@cluster.mongodb.net', dbName: 'mastra_storage', indexes: [ { collection: 'mastra_threads', keys: { 'metadata.type': 1 } }, { collection: 'mastra_messages', keys: { 'metadata.status': 1 }, options: { sparse: true } }, ], }) // For CI/CD with explicit initialization const store4 = new MongoDBStore({ id: 'mongodb-storage-04', uri: 'mongodb+srv://user:password@cluster.mongodb.net', dbName: 'mastra_storage', disableInit: true, // Disable auto-init }) await store4.init() // Call init explicitly ``` ## 其他说明 ### Collection 管理 storage 实现会自动处理 collection 的创建和管理。它会创建以下 collection: - `mastra_workflow_snapshot`:存储 workflow 状态和执行数据 - `mastra_evals`:存储评估结果和元数据 - `mastra_threads`:存储对话 thread - `mastra_messages`:存储单条 message - `mastra_traces`:存储 telemetry 和 tracing 数据 - `mastra_scorers`:存储评分和评估数据 - `mastra_resources`:存储 resource working memory 数据 - `mastra_notifications`:存储通知收件箱记录和投递元数据 `MongoDBStore` 通过 `getStore('notifications')` 提供通知存储。 ### 初始化 将 storage 传递给 Mastra class 时,任何 storage 操作前都会自动调用 `init()`: ```typescript import { Mastra } from '@mastra/core' import { MongoDBStore } from '@mastra/mongodb' const storage = new MongoDBStore({ id: 'mongodb-storage', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DB_NAME, }) const mastra = new Mastra({ storage, // init() is called automatically }) ``` 如果不通过 Mastra 直接使用 storage,则必须显式调用 `init()` 以创建 collection: ```typescript import { MongoDBStore } from '@mastra/mongodb' const storage = new MongoDBStore({ id: 'mongodb-storage', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DB_NAME, }) // Required when using storage directly await storage.init() // Access domain-specific stores via getStore() const memoryStore = await storage.getStore('memory') const thread = await memoryStore?.getThreadById({ threadId: '...' }) ``` > **注意:** 如果未调用 `init()`,将不会创建 collection,storage 操作会静默失败或抛出错误。 ### 连接管理 `close()` 方法会关闭 MongoDB client 连接。关闭应用程序时请调用它: ```typescript import { MongoDBStore } from '@mastra/mongodb' const storage = new MongoDBStore({ id: 'mongodb-storage', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DB_NAME, }) // Use storage... // Clean up on shutdown await storage.close() ``` ## 向量搜索功能 MongoDB storage 包含面向 AI 应用程序的内置向量搜索功能。有关 index 创建、upsert embedding、相似度搜索和元数据过滤等详细向量操作,请参阅 [MongoDB vector 参考](https://mastra.zisheng.pro/reference/vectors/mongodb)。 ## 使用示例 ### 向 agent 添加 memory 要向 agent 添加 MongoDB memory,请使用 `Memory` class 并通过 `MongoDBStore` 创建新的 `storage` key。该配置同时支持本地和远程 MongoDB 实例。 ```typescript import { Memory } from '@mastra/memory' import { Agent } from '@mastra/core/agent' import { MongoDBStore } from '@mastra/mongodb' export const mongodbAgent = new Agent({ id: 'mongodb-agent', name: 'mongodb-agent', instructions: 'You are an AI agent with the ability to automatically recall memories from previous interactions.', model: 'openai/gpt-5.6-sol', memory: new Memory({ storage: new MongoDBStore({ id: 'mongodb-storage', uri: process.env.MONGODB_URI!, dbName: process.env.MONGODB_DB_NAME!, }), options: { generateTitle: true, }, }), }) ``` ### 使用 agent 使用 `memoryOptions` 限定此请求的 recall 范围。设置 `lastMessages: 5` 以限制基于近期性的 recall,并使用 `semanticRecall` 获取最相关的 `topK: 3` 条 message,其中包含每个匹配项周围作为上下文的 `messageRange: 2` 条相邻 message。 ```typescript 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) } ```