跳至主要內容

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
用於進階設定的 MongoDB 用戶端選項(SSL、連線池等)。請參閱連線選項

disableInit?:

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

skipDefaultIndexes?:

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

indexes?:

MongoDBIndexConfig[]
初始化期間要建立的自訂索引。每個索引必須指定集合、鍵及可選的索引選項。請參閱索引

connectorHandler?:

ConnectorHandler
用於進階連線管理的自訂連線處理器,可取代直接提供 uri/dbName。
棄用通知

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

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 限定此要求的 recall 範圍。設定 lastMessages: 5 以限制按最近時間進行的 recall,並使用 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)
}