跳至主要內容

MongoDB 儲存空間

MongoDB 儲存空間實作採用 MongoDB 資料庫,提供大容量儲存解決方案,同時支援文件儲存與向量操作。

安裝
「安裝」的直接連結

npm install @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:

string
此儲存空間執行個體的唯一識別碼。

uri:

string
MongoDB 連線字串(例如 mongodb+srv://user:password@cluster.mongodb.net)

url?:

string
已棄用。請改用 uri。MongoDB 連線字串(為維持向後相容性而支援)。

dbName:

string
希望儲存空間使用的資料庫名稱。

options?:

MongoClientOptions
用於進階設定(SSL、連線池等)的 MongoDB client 選項。請參閱連線選項

disableInit?:

boolean
設為 true 時,會停用自動初始化(建立 collection)。適合需要明確執行 migration 的 CI/CD pipeline。此值為 true 時,必須手動呼叫 storage.init()。

skipDefaultIndexes?:

boolean
設為 true 時,初始化期間不會建立預設索引。適合另行管理索引,或只使用自訂索引時使用。

indexes?:

MongoDBIndexConfig[]
初始化期間要建立的自訂索引。每個索引都必須指定 collection、key 與選用的索引選項。請參閱索引

connectorHandler?:

ConnectorHandler
用於進階連線管理的自訂連線 handler。可用來替代直接提供 uri/dbName。
棄用通知

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:儲存評估結果與 metadata
  • mastra_threads:儲存對話 thread
  • mastra_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 執行個體。

src/mastra/agents/example-mongodb-agent.ts
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 筆相鄰訊息,作為各配對結果的上下文。

src/test-mongodb-agent.ts
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)
}