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。
Constructor 範例Constructor 範例 的直接連結
你可以透過以下方式建立 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
補充說明補充說明 的直接連結
集合管理集合管理 的直接連結
此儲存空間實作會自動處理集合的建立及管理,並建立以下集合:
mastra_workflow_snapshot:儲存 Workflow 狀態及執行資料mastra_evals:儲存評估結果及 metadatamastra_threads:儲存對話 threadmastra_messages:儲存個別訊息mastra_traces:儲存遙測及 tracing 資料mastra_scorers:儲存評分及評估資料mastra_resources:儲存資源的 working memory 資料mastra_notifications:儲存通知收件箱記錄及傳送 metadata
MongoDBStore 透過 getStore('notifications') 提供通知儲存空間。
初始化初始化 的直接連結
將儲存空間傳入 Mastra class 時,系統會在任何儲存操作前自動呼叫 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,你必須明確呼叫 init() 以建立集合:
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(),系統便不會建立集合,儲存操作會在沒有提示的情況下失敗或擲回錯誤。
連線管理連線管理 的直接連結
close() 方法會關閉 MongoDB 用戶端連線。關閉應用程式時請呼叫此方法:
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 儲存空間內置適用於 AI 應用程式的向量搜尋功能。有關建立索引、upsert embedding、相似度搜尋及 metadata 篩選等詳細向量操作,請參閱 MongoDB 向量參考。
用法範例用法範例 的直接連結
為 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 則訊息;當中亦會包括 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)
}