Overview
You can use MongoDB with Mastra AI agents to retrieve data, store past interactions, and search indexed content. MongoDB supports the following Mastra agent features:
RAG with AI Agents: Configure an agent to retrieve relevant data by using MongoDB Vector Search
Memory with AI Agents: Store your agent's conversation history in MongoDB
Workspace Search: Index text in an agent's workspace, and search the text by using BM25 keyword, vector, or hybrid search
Tip
To learn how to use MongoDB as a vector store and install the required @mastra/mongodb and @mastra/voyageai packages, see Integrate MongoDB with Mastra.
RAG with AI Agents
You can use MongoDB as a vector store within Mastra AI agents to implement agentic RAG. This allows your agents to use MongoDB vector search as a tool to help complete tasks.
Mastra also provides a MONGODB_PROMPT constant that you can include in your agent instructions to optimize how the agent uses MongoDB for retrieval. To learn more, see Vector Store Prompts.
Usage
The following example shows how to create an AI agent with RAG capabilities using MongoDB as a vector store:
import { Agent } from '@mastra/core/agent';import { openai } from '@ai-sdk/openai';import { voyageEmbedding } from '@mastra/voyageai';import { MONGODB_PROMPT } from "@mastra/mongodb";import { createVectorQueryTool } from "@mastra/rag";
// Create a vector query tool for the agentconst vectorQueryTool = createVectorQueryTool({ vectorStoreName: "mongoVector", // Name of MongoDB vector store indexName: "vector_index", // Name of Vector Search index model: voyageEmbedding({ // Embedding model model: "voyage-4", baseUrl: "https://ai.mongodb.com/v1", // MongoDB-hosted embedding endpoint }),});
// Define an AI agent with RAG capabilitiesexport const ragAgent = new Agent({ name: 'RAG Agent', // Agent name model: openai('gpt-4o-mini'), // LLM model instructions: ` Process queries using the provided context. Structure responses to be concise and relevant. ${MONGODB_PROMPT} `, tools: { vectorQueryTool }, // Tools available to the agent});Memory with AI Agents
You can use Mastra's memory system with MongoDB as the storage backend. This allows your agent to remember past interactions and use that information to inform future decisions.
For a complete tutorial, see Memory with MongoDB.
Usage
This example demonstrates how to use memory with AI agents. The code uses the options field of the memory object to scope recall for the request. Set lastMessages: 5 to include only the 5 most recent messages in the agent's context.
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, options: { lastMessages: 5 } }}); for await (const chunk of stream.textStream) { process.stdout.write(chunk);}Semantic Recall
Mastra's semantic recall feature retrieves previous messages whose meaning is similar to the user's latest message. Then, Mastra adds the most relevant previous messages to the agent's context. Use this feature when the agent requires details that are no longer in recent message history.
By default, semantic recall generates embeddings by using the model that you set on the embedder option of the Memory object. If you use Automated Embedding, MongoDB generates the embeddings instead, and your application does not need an embedder.
The following example configures semantic recall. Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
This example sets the following options:
autoEmbed: Instructs MongoDB to generate embeddings by using thevoyage-4model.semanticRecall: Enables semantic recall for the agent's memory, and sets the nestedtopKandmessageRangeoptions to refine the recall results. To learn more aboutsemanticRecalloptions, see Recall Configuration in the Mastra documentation.
import { Memory } from '@mastra/memory'import { MongoDBStore, MongoDBVector } from '@mastra/mongodb'
const semanticRecallMemory = new Memory({ storage: new MongoDBStore({ id: 'agent-storage', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DATABASE, }), vector: new MongoDBVector({ id: 'agent-vector', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DATABASE, autoEmbed: { model: 'voyage-4' }, // MongoDB generates the embeddings }), options: { semanticRecall: { topK: 3, messageRange: 2 }, },})This example sets the following options:
embedder: Instructs Mastra to generate embeddings by using thevoyage-4model. ThebaseUrloption targets the MongoDB-hosted embedding endpoint.semanticRecall: Enables semantic recall for the agent's memory, and sets the nestedtopKandmessageRangeoptions to refine the recall results. To learn more aboutsemanticRecalloptions, see Recall Configuration in the Mastra documentation.
import { Memory } from '@mastra/memory'import { MongoDBStore, MongoDBVector } from '@mastra/mongodb'import { voyageEmbedding } from '@mastra/voyageai'
const semanticRecallMemory = new Memory({ storage: new MongoDBStore({ id: 'agent-storage', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DATABASE, }), vector: new MongoDBVector({ id: 'agent-vector', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DATABASE, }), embedder: voyageEmbedding({ model: 'voyage-4', baseUrl: 'https://ai.mongodb.com/v1', // MongoDB-hosted embedding endpoint }), options: { semanticRecall: { topK: 3, messageRange: 2 }, },})When you use semantic recall, the following considerations apply:
Semantic recall requires either an embedder or a vector store that generates embeddings. If you configure neither, Mastra raises an error.
Mastra creates an MongoDB Vector Search index the first time your agent uses memory. Before you use semantic recall, ensure that your index status is
READY.
Note
Data Security
When you use Automated Embedding, MongoDB Vector Search forwards the indexed message text and each recall query to a Voyage AI service managed by MongoDB. This processing occurs outside your application, and the text may include what end users send to the agent.
By default, semantic recall searches messages from every thread that belongs to the resource value that you pass in each request. To limit the search to the current thread, set the scope option in the semanticRecall object to 'thread'.
Observational Memory
Mastra's Observational Memory feature summarizes older messages in a thread into observations. As a result, your agent's context remains small as the thread grows. You can store observations in MongoDB and search them semantically.
To enable Observational Memory, specify the observationalMemory option in your Memory object. Set this option to true to apply the default settings, or set it to a configuration object to customize the settings.
The following example configures Observational Memory. Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
This example performs the following actions:
Specifies the
observationalMemoryoption, which enables Observational MemorySpecifies the
retrievaloption, which gives an agent access to the raw messages that an observation summarizesSets the nested
vectoroption totrue, which enables semantic search on observations. MongoDB generates the embeddings.
import { Memory } from '@mastra/memory'import { MongoDBStore, MongoDBVector } from '@mastra/mongodb'
const observationalMemory = new Memory({ storage: new MongoDBStore({ id: 'agent-storage', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DATABASE, }), vector: new MongoDBVector({ id: 'agent-vector', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DATABASE, autoEmbed: { model: 'voyage-4' }, // MongoDB generates the embeddings }), options: { observationalMemory: { retrieval: { vector: true }, }, },})This example performs the following actions:
Specifies the
observationalMemoryoption, which enables Observational MemorySpecifies the
retrievaloption, which gives an agent access to the raw messages that an observation summarizesSets the nested
vectoroption totrue, which enables semantic search on observations. Theembedderoption specifies the model that generates the embeddings in your application.
import { Memory } from '@mastra/memory'import { MongoDBStore, MongoDBVector } from '@mastra/mongodb'import { voyageEmbedding } from '@mastra/voyageai'
const observationalMemory = new Memory({ storage: new MongoDBStore({ id: 'agent-storage', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DATABASE, }), vector: new MongoDBVector({ id: 'agent-vector', uri: process.env.MONGODB_URI, dbName: process.env.MONGODB_DATABASE, }), embedder: voyageEmbedding({ model: 'voyage-4', baseUrl: 'https://ai.mongodb.com/v1', // MongoDB-hosted embedding endpoint }), options: { observationalMemory: { retrieval: { vector: true }, }, },})Note
Data Security
Observations summarize end-user conversation content. When you enable semantic search, MongoDB Vector Search forwards observation text and each search query to a Voyage AI service managed by MongoDB. This processing occurs outside your application.
By default, the agent can use retrieval to access every thread of the resource. To limit the agent's access to the current thread, set the scope option in the retrieval object to 'thread'.
Workspace Search
You can use Mastra's Workspace class to provide an agent with an environment, such as a filesystem or a sandbox, and an optional MongoDB Vector Search index. A workspace searches the text that you index by using BM25 keyword, vector, or hybrid search. You can use MongoDB as the vector store for vector and hybrid search. If you use Automated Embedding, MongoDB generates the embeddings for stored text and search queries, and your application does not need a separate embedder.
To learn more about Mastra workspaces, see the Workspace class reference in the Mastra documentation.
Important
To use workspace search, you must use @mastra/core version 1.82.0 or later.
Configure Your Vector Store
To use MongoDB as your vector store, set your workspace's vectorStore option to a MongoDBVector instance. Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
To use Automated Embedding, pass the autoEmbed option to the MongoDBVector constructor. Set the nested model option to the Voyage AI model that you want to use.
import { LocalFilesystem, Workspace } from '@mastra/core/workspace'import { MongoDBVector } from '@mastra/mongodb'
const workspace = new Workspace({ id: 'movie-docs', filesystem: new LocalFilesystem({ basePath: './workspace' }), vectorStore: new MongoDBVector({ id: 'workspace-vector', uri: process.env.MONGODB_URI!, dbName: process.env.MONGODB_DATABASE!, autoEmbed: { model: 'voyage-4' }, // MongoDB generates the embeddings }),})To manually embed your text, set your workspace's embedder option to a function that returns the embedding for one text input. Mastra generates the embeddings in your application and creates the MongoDB Vector Search index with the dimensions of your embedding model.
import { LocalFilesystem, Workspace } from '@mastra/core/workspace'import { MongoDBVector } from '@mastra/mongodb'import { voyageEmbedding } from '@mastra/voyageai'import { embed } from 'ai'
const embedderModel = voyageEmbedding({ model: 'voyage-4', baseUrl: 'https://ai.mongodb.com/v1', // MongoDB-hosted embedding endpoint})
const manualWorkspace = new Workspace({ id: 'movie-docs', filesystem: new LocalFilesystem({ basePath: './workspace' }), vectorStore: new MongoDBVector({ id: 'workspace-vector', uri: process.env.MONGODB_URI!, dbName: process.env.MONGODB_DATABASE!, }), embedder: async (text: string) => { const { embedding } = await embed({ model: embedderModel, value: text }) return embedding },})Index Your Data
To add content to the search index, use the index() method. Pass an ID for the content and the text you want to index, as shown in the following example:
await workspace.index( '/movies/inception.md', 'A thief steals corporate secrets through dream-sharing technology.',)await workspace.index( '/movies/casablanca.md', 'A nightclub owner in wartime Morocco must choose between love and helping a former lover escape.',)Search Your Data
To retrieve content from the index, use the search() method. The following example runs a MongoDB Vector Search query for content that is conceptually similar to the query:
const results = await workspace.search('film about stealing ideas from dreams', { topK: 3, mode: 'vector',})
for (const result of results) { console.log(`${result.id}: ${result.score}`) console.log(result.content)}To combine keyword and vector results, run a hybrid search. Mastra stores the BM25 index in your application's memory, and MongoDB runs the MongoDB Vector Search query. Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
const hybridWorkspace = new Workspace({ id: 'movie-docs-hybrid', filesystem: new LocalFilesystem({ basePath: './workspace' }), bm25: true, vectorStore: new MongoDBVector({ id: 'workspace-vector-hybrid', uri: process.env.MONGODB_URI!, dbName: process.env.MONGODB_DATABASE!, autoEmbed: { model: 'voyage-4' }, }),})
await hybridWorkspace.index( '/movies/inception.md', 'A thief steals corporate secrets through dream-sharing technology.',)
const hybridResults = await hybridWorkspace.search('dream heist', { mode: 'hybrid', vectorWeight: 0.5,})const manualHybridWorkspace = new Workspace({ id: 'movie-docs-hybrid', filesystem: new LocalFilesystem({ basePath: './workspace' }), bm25: true, vectorStore: new MongoDBVector({ id: 'workspace-vector-hybrid', uri: process.env.MONGODB_URI!, dbName: process.env.MONGODB_DATABASE!, }), embedder: async (text: string) => { const { embedding } = await embed({ model: embedderModel, value: text }) return embedding },})
await manualHybridWorkspace.index( '/movies/inception.md', 'A thief steals corporate secrets through dream-sharing technology.',)
const manualHybridResults = await manualHybridWorkspace.search('dream heist', { mode: 'hybrid', vectorWeight: 0.5,})If you omit the mode option, Mastra uses hybrid search when you specify both bm25 and vectorStore workspace options. To learn more about workspace search options, see Search and indexing in the Mastra documentation.
Considerations
When you use Automated Embedding with workspace search, the following considerations apply:
Mastra creates the MongoDB Vector Search index the first time you index content. The index name is
_search_selfembedprefixed with the workspaceidvalue, unless you set thesearchIndexNameworkspace option.MongoDB generates embeddings asynchronously, and the first index build can take several minutes. Before running a MongoDB Vector Search query, ensure that the index status is
READY.BM25 indexes are not persistent. After your application restarts, call
index()again to rebuild the BM25 index for hybrid search. Vector embeddings and MongoDB Vector Search indexes persist in MongoDB.
Learn More
To learn more about using Mastra agents with MongoDB, see the following resources: