For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.

Integrate MongoDB with Mastra

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.

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.

To use MongoDB with Mastra, install the @mastra/mongodb package:

npm install @mastra/mongodb

To get started with Mastra and learn how to create a project, see Install Mastra.

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-node

To run these manual embedding examples, set a Voyage AI API key created in Atlas.

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.

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.

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.

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.

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 queryVector parameter is supported, but it is mutually exclusive with queryText. Ensure that the specified vector matches the index's quantization and comes from a compatible embedding model.

  • The includeVector parameter is not supported. MongoDB stores the generated vectors outside your collection, so there is no vector on the document to include.

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 }, },});

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.

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.

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,});

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.

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 } },});

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.

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 MongoDBVector created, 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 MongoDBVector created. 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.

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";

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",});

When you create a reranker, you can set the following configuration options:

Option
Description

model

(Required) The reranking model to use. To view the available models, see Rerankers in the Voyage AI documentation.

apiKey

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 VOYAGE_API_KEY environment variable.

baseUrl

The endpoint for the Voyage API. Defaults to https://api.voyageai.com/v1, the Voyage AI endpoint.

truncation

Whether to truncate inputs that exceed the model's context length. Defaults to true.

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

results

QueryResult[]

Yes

Results returned by your MongoDB Vector Search query.

query

string

Yes

Original search query.

scorer

RelevanceScoreProvider

Yes

Reranker to use.

options

RerankerFunctionOptions

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});

Tip

To learn more about reranking vector search results, see the following resources:

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 filterFields parameter 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.

1

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.

2

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,});

To learn more about using Mastra with MongoDB, see: