MongoDB
The MongoDB storage implementation provides a high-capacity storage solution using MongoDB databases with support for both document storage and vector operations.
InstallationInstallation的直接链接
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/mongodb@latest
pnpm add @mastra/mongodb@latest
yarn add @mastra/mongodb@latest
bun add @mastra/mongodb@latest
UsageUsage的直接链接
Ensure you have a MongoDB Atlas Local (via Docker) or MongoDB Atlas Cloud instance with MongoDB Search enabled. MongoDB 7.0+ is recommended.
import { MongoDBStore } from '@mastra/mongodb'
const storage = new MongoDBStore({
id: 'mongodb-storage',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DB_NAME,
})
ParametersParameters的直接链接
id:
uri:
url?:
uri instead. MongoDB connection string (supported for backward compatibility).dbName:
options?:
disableInit?:
skipDefaultIndexes?:
indexes?:
connectorHandler?:
The url parameter is deprecated but still supported for backward compatibility. Please use uri instead in all new code.
Constructor examplesConstructor examples的直接链接
You can instantiate MongoDBStore in the following ways:
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
Additional notesAdditional notes的直接链接
Collection ManagementCollection Management的直接链接
The storage implementation handles collection creation and management automatically. It creates the following collections:
mastra_workflow_snapshot: Stores workflow state and execution datamastra_evals: Stores evaluation results and metadatamastra_threads: Stores conversation threadsmastra_messages: Stores individual messagesmastra_traces: Stores telemetry and tracing datamastra_scorers: Stores scoring and evaluation datamastra_resources: Stores resource working memory datamastra_notifications: Stores notification inbox records and delivery metadata
MongoDBStore exposes notification storage through getStore('notifications').
InitializationInitialization的直接链接
When you pass storage to the Mastra class, init() is called automatically before any storage operation:
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
})
If you're using storage directly without Mastra, you must call init() explicitly to create the collections:
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: '...' })
If init() isn't called, collections won't be created and storage operations will fail silently or throw errors.
Connection ManagementConnection Management的直接链接
The close() method closes the MongoDB client connection. Call this when shutting down your application:
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()
Vector search capabilitiesVector search capabilities的直接链接
MongoDB storage includes built-in vector search capabilities for AI applications. For detailed vector operations including index creation, upserting embeddings, similarity search, and metadata filtering, see the MongoDB vector reference.
Usage exampleUsage example的直接链接
Adding memory to an agentAdding memory to an agent的直接链接
To add MongoDB memory to an agent use the Memory class and create a new storage key using MongoDBStore. The configuration supports both local and remote MongoDB instances.
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,
},
}),
})
Using the agentUsing the agent的直接链接
Use memoryOptions to scope recall for this request. Set lastMessages: 5 to limit recency-based recall, and use semanticRecall to fetch the topK: 3 most relevant messages, including messageRange: 2 neighboring messages for context around each match.
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)
}