You can integrate MongoDB with Mastra to store and search vector embeddings for your AI applications. Mastra is an open-source TypeScript agent framework that provides primitives for building AI applications, including workflows, RAG, and evals.
To learn more, see the Mastra documentation or the Mastra GitHub repository.
Overview
You can use MongoDB as a vector store in Mastra. By combining MongoDB Vector Search with the Mastra MongoDBVector class, you can implement the following capabilities:
Store and retrieve vector embeddings using MongoDB as your vector database
Filter your vector search results using MongoDB query syntax
Rerank your search results
Run a hybrid search that combines semantic and full-text search
To use MongoDB with Mastra agents, including agentic RAG, agent memory, and workspace search, see Use Mastra Agents with MongoDB.
Installation
To use MongoDB with Mastra, install the @mastra/mongodb package:
npm install @mastra/mongodbTo get started with Mastra and learn how to create a project, see Install Mastra.
Manual Embedding
The Manual Embedding examples on this page use the @mastra/voyageai package. Examples that call the voyageEmbedding() function count tokens locally before each request, which requires a tokenizer. Before running these examples, install the following packages:
npm install @mastra/voyageai @huggingface/transformers onnxruntime-nodeTo run these manual embedding examples, set a Voyage AI API key created in Atlas.
Vector Store Configuration
MongoDB is a supported database in Mastra. The MongoDBVector class allows you to store and retrieve vector embeddings from MongoDB. You can use this component to implement RAG by storing embeddings from your data and retrieving them using MongoDB Vector Search.
This component requires that you create an MongoDB Vector Search Index.
To use the MongoDB vector store with Mastra, import the MongoDBVector class, create an object with the class, and specify your MongoDB connection details. For example:
import { MongoDBVector } from '@mastra/mongodb'
// Instantiate MongoDB as a vector storeconst mongoVector = new MongoDBVector({ id: 'mongodb-vector', // Unique identifier for this vector store instance uri: process.env.MONGODB_URI, // MongoDB connection string dbName: process.env.MONGODB_DATABASE // Database name})The examples in the following sections use this MongoDBVector instance.
Methods
This section highlights the most relevant methods for working with MongoDB as a vector store. For a full list of methods, see the Mastra documentation.
MongoDB supports the following embedding modes:
Automated Embedding: MongoDB uses a Voyage AI model to automatically generate vector embeddings for your text data and your query string. To learn more, see Automated Embedding in the MongoDB Vector Search documentation.
Manual Embedding: Generate the vector embeddings yourself by managing the embedding model, the index dimensions, and the embedding operation. To learn more, see Create Vector Embeddings Manually in the MongoDB Vector Search documentation.
createIndex()
Before you can search your vector embeddings, you must create a MongoDB Vector Search index on your collection and wait for the index to become queryable. Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
To enable Automated Embedding, pass the autoEmbed parameter to the createIndex() method, as shown in the following example:
await mongoVector.createIndex({ indexName: "vector_index", autoEmbed: { model: "voyage-4" }, // Voyage AI embedding model filterFields: ["year"],});
// Waits for the index to finish building before writing to itawait mongoVector.waitForIndexReady({ indexName: "vector_index", timeoutMs: 300000,});To view the autoEmbed object fields, see Automated Embedding in the Mastra documentation.
The following example creates a MongoDB Vector Search index with 1024 dimensions:
// Create a vector search indexawait mongoVector.createIndex({ indexName: "vector_index", // Name of the index dimension: 1024, // Must match your embedding model's dimensions});
// Waits for the index to finish building before writing to itawait mongoVector.waitForIndexReady({ indexName: "vector_index", timeoutMs: 300000,});The dimension parameter must match the number of dimensions required by your embedding model.
upsert()
After creating your MongoDB Vector Search index, you can store embeddings with associated metadata. Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
To have MongoDB automatically embed your text, pass the text in the documents parameter, as shown in the following example:
await mongoVector.upsert({ indexName: "vector_index", documents: [ "A lonely astronaut adrift near a strange ocean planet.", "A heist crew robs a bank vault in Paris.", ], metadata: [{ year: 1972 }, { year: 2001 }],});On an autoEmbed index, the upsert() method rejects the vectors parameter because MongoDB generates the vectors automatically.
The following example manually generates and stores embeddings in MongoDB:
import { MDocument } from "@mastra/rag";import { voyageEmbedding } from "@mastra/voyageai";import { embedMany } from "ai";
const embeddingModel = voyageEmbedding({ model: "voyage-4", baseUrl: "https://ai.mongodb.com/v1", // MongoDB-hosted embedding endpoint});
// Create a document from textconst doc = MDocument.fromText("Your text content...");
// Split document into chunksconst chunks = await doc.chunk();
// Generate embeddings for each chunkconst { embeddings } = await embedMany({ values: chunks.map(chunk => chunk.text), // Text content to embed model: embeddingModel, // Embedding model});
// Store vector embeddings with metadataawait mongoVector.upsert({ indexName: "vector_index", // Name of the vector search index vectors: embeddings, // Array of vector embeddings metadata: chunks?.map(chunk => ({ text: chunk.text })), // Associated metadata for each embedding});query()
To retrieve semantically similar documents, run a MongoDB Vector Search query by using the query() method. Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
To run a MongoDB Vector Search query, pass the queryText parameter to the query() method. MongoDB embeds the query text at search time.
const results = await mongoVector.query({ indexName: "vector_index", queryText: "space opera about isolation", topK: 5, filter: { year: { $gt: 1970 } },});After you upsert documents, MongoDB generates embeddings asynchronously. Depending on the amount of data, it can take time for the documents to be indexed and available for semantic search. On large collections, the first embedding can take several hours to complete.
When using Automated Embedding, the following restrictions apply:
The
queryVectorparameter is supported, but it is mutually exclusive withqueryText. Ensure that the specified vector matches the index'squantizationand comes from a compatible embedding model.The
includeVectorparameter is not supported. MongoDB stores the generated vectors outside your collection, so there is no vector on the document to include.
The following example manually generates embeddings for a query string and then runs a MongoDB Vector Search query:
import { voyageEmbedding } from "@mastra/voyageai";import { embed } from "ai";
const embeddingModel = voyageEmbedding({ model: "voyage-4", baseUrl: "https://ai.mongodb.com/v1", // MongoDB-hosted embedding endpoint});
// Convert query to embeddingconst { embedding } = await embed({ value: "What are the main points in the article?", // Query text model: embeddingModel, // Embedding model});
// Query the vector store for similar documentsconst results = await mongoVector.query({ indexName: "vector_index", // Name of the vector search index queryVector: embedding, // Query embedding vector topK: 10, // Number of results to return});
// Display resultsconsole.log(results);To learn more, see Retrieval in Mastra.
Metadata Filtering
The MongoDB vector store supports metadata filtering on your vector search query results:
Use the Mastra query syntax.
Use standard comparison, array, logical, and element operators
Use nested fields and arrays in metadata
Filter on metadata and the contents of the original documents
The following usage example demonstrates the filtering syntax. Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
To use Automated Embedding, pass the query text in the queryText parameter. MongoDB embeds the text when you run the query.
const filteredResults = await mongoVector.query({ indexName: "vector_index", queryText: "heist movie set in Paris", topK: 10, filter: { year: { $gte: 1990, $lte: 2010 }, },});To manually embed your query text, pass the resulting embedding in the queryVector parameter.
const filteredResults = await mongoVector.query({ indexName: "vector_index", // Name of the vector search index queryVector: queryVector, // Query embedding vector topK: 10, // Number of results to return filter: { year: { $gte: 1990, $lte: 2010 }, // Range comparison },});Tip
For optimal performance, create indexes on metadata fields that you frequently filter on. To learn more, see MongoDB Vector Search Indexes.
To learn more, see Metadata Filters.
Existing Collection Indexes
You can create a MongoDB Vector Search index on an existing MongoDB collection, instead of copying the data into a collection that Mastra manages. To specify the collection, pass the collectionName parameter to the createIndex() method. These examples require @mastra/mongodb version 1.28.0 or later.
Note
A new index on an existing collection is read-only by default. The upsert(), updateVector(), deleteVector(), and deleteVectors() methods generate an error instead of modifying your documents. To store embeddings, write them to your corresponding documents from your application, or use Automated Embedding.
Create the Index
Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
The following example creates an autoEmbed index on the existing movies collection's plot field:
await mongoVector.createIndex({ indexName: "movies_index", collectionName: "movies", autoEmbed: { model: "voyage-4", path: "plot" }, filterFields: ["year"],});
await mongoVector.waitForIndexReady({ indexName: "movies_index", timeoutMs: 300000,});The following example creates a vector index on the existing movies collection's embedding field:
await mongoVector.createIndex({ indexName: "movies_index", collectionName: "movies", dimension: 1024, filterFields: ["year"],});
await mongoVector.waitForIndexReady({ indexName: "movies_index", timeoutMs: 300000,});Your documents must already contain the vector embeddings in an embedding field. To store embeddings in a different field, set the embeddingFieldPath option in the MongoDBVector constructor.
Note
Data Security
When you use Automated Embedding on an existing collection, MongoDB Vector Search forwards the text in the indexed field and each text query to a Voyage AI service managed by MongoDB. This processing occurs outside your application.
Query the Index
By default, query results from an existing collection include the id and score fields. For an autoEmbed index, results also include the indexed text in the document field. To retrieve the full document in the metadata field of each result, set the metadataMode parameter to "document".
Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
The following example queries the movies collection for documents that match the specified query text:
const results = await mongoVector.query({ indexName: "movies_index", queryText: "space opera about isolation", topK: 5, metadataMode: "document", filter: { year: { $gt: 1970 } },});The following example queries the movies collection for documents that match the specified embedding:
import { voyageEmbedding } from "@mastra/voyageai";
const voyage = voyageEmbedding({ model: "voyage-4", baseUrl: "https://ai.mongodb.com/v1", inputType: "query",});
const { embeddings } = await voyage.doEmbed({ values: ["space opera about isolation"],});const queryEmbedding = embeddings[0];
const results = await mongoVector.query({ indexName: "movies_index", queryVector: queryEmbedding, topK: 5, metadataMode: "document", filter: { year: { $gt: 1970 } },});By default, results omit the embedding from the metadata field. To include it, set the includeVector parameter to true.
Tip
Filter Fields
The preceding example filters documents by the year field, which the createIndex() example declares in the filterFields parameter. If you filter on a field that you don't declare in filterFields, or use an operator that $vectorSearch doesn't support, MongoDBVector filters the results in two steps. The vector store first runs a separate $match query and loads the matching _id values into memory. Then, the store passes those values to MongoDB Vector Search.
These additional steps increase costs and latency, since the $match query runs a collection scan unless a regular MongoDB index covers the filtered fields. If more than 100,000 documents match the filter, the query throws a TOO_MANY_CANDIDATES error.
Delete the Index
To delete a MongoDB Vector Search index, call the deleteIndex() method and pass the same indexName value that you passed to createIndex(). The method behavior differs depending on collection ownership:
Mastra collection: This method deletes the entire collection that
MongoDBVectorcreated, including its documents. If another index uses the collection, the method throws an error and has no effect.Existing MongoDB collection: This method deletes only the MongoDB Vector Search and full-text indexes that
MongoDBVectorcreated. Your collection, documents, and other indexes remain.
The following example deletes the movies_index index:
await mongoVector.deleteIndex({ indexName: "movies_index" });If you pass an index name that the createIndex() method didn't register, the method throws an error and does not delete anything.
Reranking
The @mastra/voyageai package provides a reranker that rescores your MongoDB Vector Search results against the original query, improving on the initial similarity ranking. This section shows how to create a reranker and use it to rescore vector search results in your application.
To run the examples in this section, add the following import statements to your code:
import { voyage, createVoyageReranker, VoyageRelevanceScorer } from "@mastra/voyageai";import { rerankWithScorer, createVectorQueryTool } from "@mastra/rag";Create a Reranker
To use the default reranker that the @mastra/voyageai package provides, access the voyage object's reranker property, as shown in the following example:
const defaultReranker = voyage.reranker;This default reranker uses the rerank-2.5 model and sends requests to the Voyage AI endpoint. If you created your API key in Atlas, use the MongoDB endpoint instead. You can use the createVoyageReranker() function or the VoyageRelevanceScorer class to create a reranker that specifies a different model or endpoint. To view an example, select the tab corresponding to your preferred method:
const customRerankerFunction = createVoyageReranker({ model: "rerank-3", baseUrl: "https://ai.mongodb.com/v1",});const customRerankerClass = new VoyageRelevanceScorer({ model: "rerank-3-lite", baseUrl: "https://ai.mongodb.com/v1",});Configuration Options
When you create a reranker, you can set the following configuration options:
Option | Description |
|---|---|
| (Required) The reranking model to use. To view the available models, see Rerankers in the Voyage AI documentation. |
| Your API key. MongoDB model API keys work only with MongoDB endpoints, and Voyage AI API keys work only with Voyage AI endpoints. Defaults to the |
| The endpoint for the Voyage API. Defaults to |
| Whether to truncate inputs that exceed the model's context length. Defaults to |
Rerank Results
After creating a reranker, you can rescore your MongoDB Vector Search results by using the rerankWithScorer() function. Alternatively, pass the reranker directly to the createVectorQueryTool() function to instruct an agent to rerank results automatically. To view an example, select the tab corresponding to your preferred method:
Pass the following arguments to the rerankWithScorer() function:
Argument | Data Type | Required | Description |
|---|---|---|---|
|
| Yes | Results returned by your MongoDB Vector Search query. |
|
| Yes | Original search query. |
|
| Yes | Reranker to use. |
|
| Yes | Configuration options for the rescore. |
const reranker = createVoyageReranker({ model: "rerank-3", baseUrl: "https://ai.mongodb.com/v1",});
const results = await rerankWithScorer({ results: vectorSearchResults, query: "How do I deploy to production?", scorer: reranker, options: { topK: 5 }, // Number of top results to return});Pass the following arguments to the createVectorQueryTool() function:
Argument | Data Type | Required | Description |
|---|---|---|---|
|
| Yes | Name of your MongoDB vector store. |
|
| Yes | Name of your MongoDB Vector Search index. |
|
| Yes | Embedding model to use. |
|
| No | Reranker to use. Defaults to no reranking. |
const toolReranker = createVoyageReranker({ model: "rerank-3", baseUrl: "https://ai.mongodb.com/v1",});
const queryTool = createVectorQueryTool({ vectorStoreName: "mongoVector", indexName: "vector_index", model: voyage.embedding({ model: "voyage-4", baseUrl: "https://ai.mongodb.com/v1", }), reranker: { model: toolReranker, options: { topK: 5 } },});Tip
To learn more about reranking vector search results, see the following resources:
Re-ranking in the Mastra documentation
Rerankers in the Voyage AI documentation
Hybrid Search
Important
Hybrid search requires MongoDB 8.0 or later.
You can use the Mastra MongoDBVector class to run a hybrid search on your data. Hybrid search combines semantic search with MongoDB Vector Search and full-text search with MongoDB Search to help improve the relevance of your search results. When your queries need both semantic matches and exact keyword matches, such as product names or error codes, use hybrid search. The hybridQuery() method runs both searches and then merges the results by using the $rankFusion stage.
To filter the results, pass a filter object that uses the same syntax as metadata filtering. MongoDB applies the filter to both searches before it merges the results, but each search applies the filter at a different point:
MongoDB Vector Search filters documents before it searches. You can declare the fields that you filter on in the
filterFieldsparameter when you create the index. If your filter uses only declared fields and operators that MongoDB Vector Search supports, MongoDB applies it inside the search. Otherwise, if the filter matches more than 100,000 documents, the query fails.MongoDB Search applies the filter after it searches. MongoDB applies the filter on the server, not in your application. A broad full-text query combined with a narrow filter can be slower.
Hybrid search requires an existing MongoDB Vector Search index that contains documents. To create the index and store documents, see the createIndex() and upsert() sections. The createIndex() method also creates a full-text search index on all fields in your collection. To index only specific fields, or to search an existing collection, use the createSearchIndex() method instead. To learn more, see createSearchIndex() in the Mastra documentation.
Before you run a hybrid search, use the waitForSearchIndexReady() method to wait for the full-text search index to be ready. Then, complete the following steps.
Run a hybrid search query.
Call the hybridQuery() method with two queries: a vector object for the MongoDB Vector Search query and a text object for the full-text query. MongoDB ranks the results of each search, and then merges the two rankings into a fusion score. MongoDB returns this score in the score field of each result.
Optionally, set the weights field to control how much each search counts toward the final order. By default, both searches count equally. To favor vector matches instead, give vector the higher weight. Each weight must be a non-negative number, and at least one weight must be greater than 0. An omitted weight defaults to 1.
The following examples search for space opera about isolation. They count full-text matches twice as heavily as vector matches and return the top 5 results.
Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
The following example passes your query text in vector.query, and MongoDB generates the query vector.
const question = "space opera about isolation";
const results = await mongoVector.hybridQuery({ indexName: "vector_index", vector: { query: question, limit: 50 }, // MongoDB embeds this text text: { query: question, paths: ["document"], limit: 50 }, // Full-text query and fields weights: { vector: 1, text: 2 }, // Counts full-text matches twice as heavily topK: 5,});The full-text query searches the document field, where MongoDB stores your text by using Automated Embedding. MongoDB sends both the text that you store and your query text to an embedding model to generate vectors. By default, the model runs on MongoDB infrastructure in any cloud provider and geography. To restrict where MongoDB processes your text, see Configure the Inference Scope.
The following example generates an embedding for your query and passes it in vector.queryVector.
import { voyageEmbedding } from "@mastra/voyageai";import { embed } from "ai";
const embeddingModel = voyageEmbedding({ model: "voyage-4", baseUrl: "https://ai.mongodb.com/v1", // MongoDB-hosted embedding endpoint});
const question = "space opera about isolation";
// Convert the question to an embeddingconst { embedding } = await embed({ value: question, model: embeddingModel,});
const results = await mongoVector.hybridQuery({ indexName: "vector_index", vector: { queryVector: embedding, limit: 50 }, // Embedding that you generated text: { query: question, paths: ["metadata.text"], limit: 50 }, // Full-text query and fields weights: { vector: 1, text: 2 }, // Counts full-text matches twice as heavily topK: 5,});The full-text query searches the metadata.text field, where the upsert() example stores your text.
(Optional) Add native reranking.
Important
Native reranking requires an Atlas cluster that runs MongoDB 9.0 or later, with Native Reranking enabled in your project settings. Reranking sends your query and the text in the rerank.paths fields to a Voyage AI reranking model, which runs outside your cluster. By default, MongoDB uses the rerank-2.5 model. To use a different model, set the rerank.model field. To learn about the requirements for each model, see Requirements.
You can refine the order of your hybrid search results by adding a rerank object to your query. MongoDB passes the merged results to a reranking model, which scores each document by its relevance to your query and reorders the results. Because the reranker sets the final order, the weights field affects only which documents MongoDB reranks.
With native reranking, MongoDB calls the reranking model as part of your hybrid search query. If your cluster doesn't meet the requirements for native reranking, you can call a reranking model from your application instead. To learn more, see Reranking.
When you enable reranking, the score field of each result contains the reranking score instead of the fusion score. The two scores use different scales.
Select the Automated Embedding or Manual Embedding tab to view an example that uses your preferred embedding mode:
The following example adds a rerank object to a hybrid search query. MongoDB reranks up to 50 merged documents based on the text in the document field, and then returns the 5 highest-scoring results. The highlighted lines show the rerank object:
// Uses question from the previous stepconst results = await mongoVector.hybridQuery({ indexName: "vector_index", vector: { query: question, limit: 50 }, text: { query: question, paths: ["document"], limit: 50 }, weights: { vector: 1, text: 2 }, // Counts full-text matches twice as heavily rerank: { query: question, // Query that the reranker scores against paths: ["document"], // Fields that the reranker reads numDocsToRerank: 50, // Maximum merged documents to rerank }, topK: 5,});The following example adds a rerank object to a hybrid search query. MongoDB reranks up to 50 merged documents based on the text in the metadata.text field, and then returns the 5 highest-scoring results. The highlighted lines show the rerank object:
// Uses question and embedding from the previous stepconst results = await mongoVector.hybridQuery({ indexName: "vector_index", vector: { queryVector: embedding, limit: 50 }, text: { query: question, paths: ["metadata.text"], limit: 50 }, weights: { vector: 1, text: 2 }, // Counts full-text matches twice as heavily rerank: { query: question, // Query that the reranker scores against paths: ["metadata.text"], // Fields that the reranker reads numDocsToRerank: 50, // Maximum merged documents to rerank }, topK: 5,});Additional Resources
To learn more about using Mastra with MongoDB, see: