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 管理」的直接連結
儲存空間實作會自動處理 collection 的建立與管理,並建立下列 collection:
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') 提供通知儲存空間。
初始化「初始化」的直接連結
將 storage 傳入 Mastra 類別時,系統會在進行任何儲存操作前自動呼叫 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 儲存空間內建適用於 AI 應用程式的向量搜尋功能。如需建立索引、upsert embedding、相似度搜尋及 metadata 篩選等詳細向量操作,請參閱 MongoDB 向量參考資料。
使用範例「使用範例」的直接連結
為 Agent 新增記憶體「為 Agent 新增記憶體」的直接連結
若要為 Agent 新增 MongoDB 記憶體,請使用 Memory 類別,並以 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 設定此請求的回憶範圍。設定 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)
}