MongoDB 存储
MongoDB 存储实现使用 MongoDB 数据库提供高容量存储解决方案,同时支持文档存储和向量操作。
安装安装的直接链接
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/mongodb@latest
pnpm add @mastra/mongodb@latest
yarn add @mastra/mongodb@latest
bun add @mastra/mongodb@latest
使用方法使用方法的直接链接
请确保你拥有已启用 Atlas Search 的 MongoDB Atlas Local(通过 Docker) 或 MongoDB Atlas Cloud 实例。建议使用 MongoDB 7.0+。
import { MongoDBStore } from '@mastra/mongodb'
const storage = new MongoDBStore({
id: 'mongodb-storage',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DB_NAME,
})
参数参数的直接链接
id:
uri:
url?:
uri。MongoDB 连接字符串(为向后兼容而支持)。dbName:
options?:
disableInit?:
skipDefaultIndexes?:
indexes?:
connectorHandler?:
url 参数已弃用,但仍为向后兼容而受支持。请在所有新代码中改用 uri。
构造函数示例构造函数示例的直接链接
你可以通过以下方式实例化 MongoDBStore:
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 管理Collection 管理的直接链接
storage 实现会自动处理 collection 的创建和管理。它会创建以下 collection:
mastra_workflow_snapshot:存储 workflow 状态和执行数据mastra_evals:存储评估结果和元数据mastra_threads:存储对话 threadmastra_messages:存储单条 messagemastra_traces:存储 telemetry 和 tracing 数据mastra_scorers:存储评分和评估数据mastra_resources:存储 resource working memory 数据mastra_notifications:存储通知收件箱记录和投递元数据
MongoDBStore 通过 getStore('notifications') 提供通知存储。
初始化初始化的直接链接
将 storage 传递给 Mastra class 时,任何 storage 操作前都会自动调用 init():
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:
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 连接。关闭应用程序时请调用它:
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 参考。
使用示例使用示例的直接链接
向 agent 添加 memory向 agent 添加 memory的直接链接
要向 agent 添加 MongoDB memory,请使用 Memory class 并通过 MongoDBStore 创建新的 storage key。该配置同时支持本地和远程 MongoDB 实例。
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使用 agent的直接链接
使用 memoryOptions 限定此请求的 recall 范围。设置 lastMessages: 5 以限制基于近期性的 recall,并使用 semanticRecall 获取最相关的 topK: 3 条 message,其中包含每个匹配项周围作为上下文的 messageRange: 2 条相邻 message。
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)
}