Skip to main content

MongoDB vector store

The MongoDBVector class provides vector search using MongoDB Vector Search. It enables efficient similarity search and metadata filtering within your MongoDB collections.

Installation
Direct link to Installation

npm install @mastra/mongodb@latest

Usage example
Direct link to Usage example

import { MongoDBVector } from '@mastra/mongodb'

const store = new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DB_NAME,
})

Custom embedding field path
Direct link to Custom embedding field path

If you need to store embeddings in a nested field structure (e.g., to integrate with existing MongoDB collections), use the embeddingFieldPath option:

import { MongoDBVector } from '@mastra/mongodb'

const store = new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DB_NAME,
embeddingFieldPath: 'text.contentEmbedding', // Store embeddings at text.contentEmbedding
})

Constructor options
Direct link to Constructor options

id:

string
Unique identifier for this vector store instance

uri:

string
MongoDB connection string

dbName:

string
Name of the MongoDB database to use

options?:

MongoClientOptions
Optional MongoDB client options

embeddingFieldPath?:

string
= embedding
Path to the field that stores vector embeddings. Supports nested paths using dot notation (e.g., 'text.contentEmbedding').

autoEmbed?:

MongoDBAutoEmbedConfig
Automated Embedding defaults for indexes this store creates, such as { model: 'voyage-4' }. An index created without its own autoEmbed or dimension uses these settings, which makes the store embed text server-side instead of receiving vectors.

Methods
Direct link to Methods

connect()
Direct link to connect

Establishes connection to the MongoDB server. This is called automatically on first use, but can be called explicitly if needed.

await store.connect()

createIndex()
Direct link to createindex

Creates a new vector index (collection) in MongoDB. When calls for the same new name run concurrently and ask for the same collection and embedding, all of them succeed. If they ask for different ones, the later call throws CONFLICT naming what differs.

indexName:

string
Name of the collection to create

dimension?:

number
Vector dimension (must match your embedding model). Required unless autoEmbed is set, where the embedding model determines the dimension. Passing both is an error.

autoEmbed?:

MongoDBAutoEmbedConfig
Generate the embeddings in MongoDB instead of supplying vectors. See Automated Embedding for the supported fields.

metric?:

'cosine' | 'euclidean' | 'dotproduct'
= cosine
Distance metric for similarity search

filterFields?:

string[]
Metadata field names to declare as filter fields in the MongoDB vectorSearch index (registered as metadata.<field>). Queries that filter only on declared fields are pushed directly into $vectorSearch instead of pre-filtering candidate _ids, avoiding the 16 MB BSON limit on large result sets. Filters that reference an undeclared field, or use an operator $vectorSearch does not support, fall back to the pre-filter automatically. On a bring-your-own index, names are declared as written (for example, lane or specs.gpu), so metadataMode: 'document' filters can use them.

collectionName?:

string
Store the vectors on an existing (operational) collection instead of a managed collection named after the index. The collection is never created or dropped by this store when set. Defaults to indexName. A managed collection is created with validationLevel: 'off', which has no effect without a validator. It lets Mastra tell a collection it created from one another client created at the same moment with other options, which Mastra adopts and never drops.

searchIndexName?:

string
Name for the MongoDB vectorSearch index created on the collection. Defaults to ${indexName}_vector_index.

allowWrites?:

boolean
= false
Deprecated, and removed in the next major version. Opts in to upsert, updateVector, deleteVector, and deleteVectors on a bring-your-own collection, which is read-only by default. Ignored for managed collections, which are always writable. The policy is persisted with the index registration and survives restarts. See the warning under Indexing an existing collection.

waitForIndexReady()
Direct link to waitforindexready

Waits for an index to become ready after creation. Useful when you need to ensure an index is ready before performing operations.

indexName:

string
Name of the index to wait for

timeoutMs?:

number
= 60000
Maximum time to wait in milliseconds

checkIntervalMs?:

number
= 2000
Interval between status checks in milliseconds

upsert()
Direct link to upsert

Adds or updates vectors and their metadata in the collection. On a bring-your-own index, this requires the deprecated allowWrites: true option at createIndex() time because BYO collections are read-only by default.

indexName:

string
Name of the collection to insert into

vectors?:

number[][]
Array of embedding vectors. Required unless the index was created with autoEmbed, where MongoDB generates them from documents and supplying vectors is an error.

metadata?:

Record<string, any>[]
Metadata for each vector

ids?:

string[]
Optional vector IDs (auto-generated if not provided)

documents?:

string[]
Document text content to store alongside vectors. On an autoEmbed index this is the text MongoDB embeds, and it is required.

query()
Direct link to query

Searches for similar vectors with optional metadata filtering.

indexName:

string
Name of the collection to search in

queryVector?:

number[]
Query vector to find similar vectors for. Supply this or queryText, not both.

queryText?:

string
Text for MongoDB to embed at query time. autoEmbed indexes only, and mutually exclusive with queryVector. For full-text matching use textQuery() instead.

model?:

string
Embedding model for this query, overriding the index's. Requires queryText, and must be compatible with the index's model.

topK?:

number
= 10
Number of results to return

filter?:

Record<string, any>
Metadata filters (applies to the metadata field)

documentFilter?:

Record<string, any>
Filters on original document fields (not just metadata)

includeVector?:

boolean
= false
Whether to include vector data in results

numCandidates?:

number
= 20 * topK (capped at 10000)
Number of candidates the HNSW graph considers before selecting top-K results. Higher values improve recall at the cost of latency. See: https://www.mongodb.com/docs/atlas/atlas-vector-search/vector-search-stage/

metadataMode?:

'field' | 'document'
= field
'field' (default) projects the managed metadata/document fields, and filter fields are matched against the metadata subdocument. 'document' returns the full source document as metadata โ€” use for bring-your-own operational collections whose documents have their own shape โ€” and filter fields are matched against the **root** document (no metadata. prefix). The embedding field is omitted from metadata by default (to avoid payload bloat); set includeVector: true to retain it in metadata and also expose it as a top-level vector.

BYO filter declarations after upgrading
Direct link to BYO filter declarations after upgrading

BYO filterFields are now declared exactly as written. Earlier versions prefixed bare declarations with metadata.. If your BYO documents store values under metadata and you use the default metadataMode: 'field', declare the full paths, such as filterFields: ['metadata.category']. Keep the query filter as { category: 'billing' }.

For root-level BYO fields, use filterFields: ['category'] with metadataMode: 'document'. If you rebuild an index with root-level declarations but still query nested metadata, filtering falls back to the bounded pre-filter instead of running inside $vectorSearch. To change an existing search index's field declarations, update its definition in MongoDB rather than registering it again. After the updated index reaches READY, create a new MongoDBVector instance and use it for subsequent queries so it loads the updated declarations instead of cached paths. Otherwise, large nested-metadata queries can continue to hit TOO_MANY_CANDIDATES even after you add the required filter paths.

Filters that can't run inside $vectorSearch
Direct link to filters-that-cant-run-inside-vectorsearch

A filter runs inside $vectorSearch only when every field it uses is declared in filterFields and every operator is one $vectorSearch supports. Otherwise query() and hybridQuery() first run the filter as a $match, load the matching _ids into memory, and pass them to $vectorSearch. Without a regular index on the filtered fields, that step scans the collection. If more than 100,000 documents match or their candidate _id array exceeds 12 MiB of BSON, the query throws TOO_MANY_CANDIDATES. The byte budget leaves room for the rest of the MongoDB command. Long string IDs can reach it before the document-count limit.

Results come back as a complete array of at most 10,000 hits. Memory use grows with topK, includeVector, and document size, and metadataMode: 'document' returns full source documents.

createSearchIndex()
Direct link to createsearchindex

Provisions a MongoDB Search (BM25/full-text) index on the collection backing an index and records it as the text-search index that textQuery() and hybridQuery() will target.

Managed vs. bring-your-own collections:

  • For a managed index (created without collectionName), createIndex() already provisions a dynamic full-text index named ${collectionName}_search_index (covering all string fields). createSearchIndex() is therefore only needed when you want a field-restricted mapping or a custom index name.
  • For a bring-your-own index (created with collectionName), createIndex() doesn't auto-create any full-text index. Enabling textQuery()/hybridQuery() on a caller-owned operational collection is opt-in. Call createSearchIndex() explicitly to provision the (billable) text index. Until you do, textQuery()/hybridQuery() throw a clear error rather than querying a non-existent index.

Naming:

  • When fields is provided without an explicit searchIndexName, the field-mapped index is created under a distinct default name (${collectionName}_${indexName}_search_fields_index, unique per logical index) so it doesn't collide with a managed collection's auto-created dynamic index and get silently ignored. This distinct index is persisted as the text-search index, so textQuery()/hybridQuery() use the restricted mapping automatically.
  • When searchIndexName is provided, that exact name is used and persisted. textQuery()/hybridQuery() resolve the persisted name automatically. You can also override the name per call via their searchIndexName / textSearchIndexName parameters.

indexName:

string
Name of the Mastra index whose collection will have the search index

fields?:

string[]
Field names to index for full-text search. Use dot notation for nested fields, for example metadata.name. Omit for dynamic mapping (all string fields).

searchIndexName?:

string
= ${collectionName}_search_index (or ${collectionName}_${indexName}_search_fields_index when `fields` is given)
Name for the MongoDB Search index. When fields is provided and this is omitted, a distinct default name that is unique per logical index is used, so the field mapping is not shadowed by the auto-created dynamic index and two logical indexes on the same collection do not collide.

waitUntilReady?:

boolean
= false
When true, block until the provisioned full-text index reports READY before resolving. Defaults to false to avoid surprising latency; call waitForSearchIndexReady() explicitly if you prefer to await separately.
await store.createSearchIndex({
indexName: 'precedents',
fields: ['note', 'description'],
})

The field-mapped index name includes the logical indexName, so two logical indexes on the same collection get distinct text indexes. Calling createSearchIndex() again for the same logical index with different fields updates the existing text index definition in place if Mastra created it. You don't need to drop it first. Mastra never changes a full-text index it didn't create: an existing index with the requested name is reused only when its whole definition is equivalent to the one requested: field types, analyzers (including the root analyzer and searchAnalyzer), nested fields, storedSource and synonyms. Defaults that Atlas echoes back, such as indexOptions: 'offsets', store: true, norms: 'include' and an empty fields, count as equivalent. Otherwise createSearchIndex() throws a CONFLICT error. When the registration predates ownership records, the message suggests claimLegacyIndex().

waitForSearchIndexReady()
Direct link to waitforsearchindexready

Waits for the full-text (BM25) search index of an index to become READY. waitForIndexReady() polls only the vectorSearch index; createSearchIndex() returns while the MongoDB Search full-text index is still building, so an immediate textQuery()/hybridQuery() can intermittently fail. Call this (or pass waitUntilReady: true to createSearchIndex()) to block until the resolved text index reports READY.

indexName:

string
Logical name of the index whose text index to wait for

searchIndexName?:

string
Override the resolved text-search index name

timeoutMs?:

number
= 60000
Maximum time to wait in milliseconds

checkIntervalMs?:

number
= 2000
Interval between status checks in milliseconds
await store.createSearchIndex({ indexName: 'precedents', fields: ['note'] })
await store.waitForSearchIndexReady({ indexName: 'precedents' })

textQuery()
Direct link to textquery

Runs a full-text (BM25) search against a MongoDB Search index. By default it targets the text-search index recorded for this index (set by createSearchIndex(), or the dynamic ${collectionName}_search_index auto-created by createIndex()). Pass searchIndexName to target a specific index for this call.

Metadata filters here (like hybridQuery()) are applied via a $match stage. For the vector branch of hybridQuery(), filters on fields not declared via filterFields at index creation are transparently materialised as candidate _ids (the same fallback query() uses), so undeclared-field filters don't error.

indexName:

string
Name of the Mastra index to search

query:

string
Full-text search query string

paths:

string[]
Field paths to search in (e.g., ["note", "description"])

topK?:

number
= 10
Number of results to return

filter?:

Record<string, any>
Metadata filters (applies to the metadata field)

metadataMode?:

'field' | 'document'
= field
'field' (default) projects the managed metadata/document fields. 'document' returns the full source document as metadata.

searchIndexName?:

string
Override the resolved full-text search index name for this call. Defaults to the index persisted by createSearchIndex() / createIndex().
const results = await store.textQuery({
indexName: 'precedents',
query: 'shell company offshore',
paths: ['note'],
topK: 10,
})

hybridQuery()
Direct link to hybridquery

Runs a hybrid search that fuses vector similarity with full-text results through MongoDB's server-side $rankFusion. The feature requires MongoDB 8.0 or later. A full-text search index must exist. Managed indexes create one automatically, while bring-your-own collections require an explicit createSearchIndex() call.

indexName:

string
Name of the Mastra index to search

queryVector?:

number[]
Query vector for the vector branch. Supply this or queryText, not both.

queryText?:

string
Text for MongoDB to embed for the vector branch. autoEmbed indexes only. Independent of query, so each branch can search for something different.

model?:

string
Embedding model for the vector branch, overriding the index's. Requires queryText.

query:

string
Full-text search query string

paths:

string[]
Field paths to search in for full-text (e.g., ["note", "description"])

topK?:

number
= 10
Number of results to return

filter?:

Record<string, any>
Metadata filters (applies to both vector and text branches)

weights?:

{ vector?: number; text?: number }
Relative weights for vector vs. text results in fusion (default: 1:1)

numCandidates?:

number
= 20 * topK (capped at 10000)
Number of candidates for the vector search branch

metadataMode?:

'field' | 'document'
= field
'field' (default) projects the managed metadata/document fields. 'document' returns the full source document as metadata.

textSearchIndexName?:

string
Override the resolved full-text search index name for this call. Defaults to the index persisted by createSearchIndex() / createIndex().
const results = await store.hybridQuery({
indexName: 'precedents',
queryVector: embedding,
query: 'shell company offshore',
paths: ['note'],
topK: 10,
weights: { vector: 1, text: 1.5 }, // Favor text matches
})

hybridQuery() requires MongoDB 8.0 or later for the $rankFusion stage. If your deployment is older or lacks $rankFusion, run query() and textQuery() separately before merging the results client-side.

Per-branch options and native reranking
Direct link to Per-branch options and native reranking

hybridQuery() also accepts separate vector and text options. Use this form to set a different retrieval limit for each branch, and optionally rerank the fused results before the final topK limit. Existing calls that use the parameters above don't change.

This form has the same $rankFusion requirements and registered indexes. For bring-your-own collections, register a full-text index with createSearchIndex() or pass text.searchIndexName.

Native $rerank requires Atlas running MongoDB 9.0 or later with Native Reranking enabled in the project's settings. The default rerank-2.5 model isn't in Preview. In native $rerank, the rerank-3 and rerank-3-lite models are in Preview and require a dedicated M10-or-higher cluster. The same models are out of Preview in the Voyage AI API. Self-managed and Atlas Local deployments don't support native reranking. No separate Voyage AI client or application-side API key is required.

With an initialized store, registered indexes, an embedding you generated, and text stored in metadata.text, retrieve candidates and rerank them in one call:

const results = await store.hybridQuery({
indexName: 'articles',
vector: { queryVector: embedding, limit: 50, numCandidates: 1000 },
text: { query: question, paths: ['metadata.text'], limit: 50 },
rerank: { query: question, paths: ['metadata.text'], numDocsToRerank: 50 },
topK: 5,
})

Each retrieval branch contributes up to its own limit documents. $rerank evaluates up to numDocsToRerank fused documents, then topK limits the response. The reranker receives source documents before projection, so text.paths and rerank.paths are relative to the document root, for both managed and bring-your-own collections.

This form has no metadataMode option. Managed indexes return the managed metadata and document fields. Bring-your-own indexes return the source document as metadata, excluding the embedding field. With includeVector: true, metadata keeps the embedding field and the result also returns it as vector.

On an autoEmbed index, use vector.query instead of vector.queryVector. Omit rerank to return fused results without reranking:

const results = await store.hybridQuery({
indexName: 'articles_auto',
vector: { query: question, limit: 50 },
text: { query: question, paths: ['document'], limit: 50 },
topK: 5,
})

indexName:

string
Logical Mastra index identifying the collection and registered search indexes.

topK?:

number
= 10
Final result limit after fusion and optional reranking. Integer from 1 to 10000.

filter?:

MongoDBVectorFilter
Filter applied to both retrieval branches before fusion. On managed indexes, keys target the managed metadata fields. On bring-your-own indexes, keys target source document fields. Filters on fields declared in filterFields run inside $vectorSearch. Other filters use the `_id` pre-filter, as in the flat form.

weights?:

{ vector?: number; text?: number }
Finite, non-negative fusion weights. Each omitted weight defaults to 1. At least one must be positive.

includeVector?:

boolean
= false
Return each result's stored embedding as vector. Not supported on autoEmbed indexes, which throw an error.

vector:

object
Vector retrieval configuration. Supply exactly one of queryVector or query.

vector.queryVector?:

number[]
Non-empty, finite embedding that you generate. Mutually exclusive with vector.query and vector.model. Not supported on autoEmbed indexes, which throw an error; use vector.query instead.

vector.query?:

string
Non-empty text for MongoDB to embed. Requires an autoEmbed index and is independent of text.query.

vector.model?:

string
Query embedding model override. Requires vector.query and must be compatible with the index model. Independent of rerank.model.

vector.limit?:

number
= min(10000, max(4 * topK, 20))
Maximum vector results contributed to fusion. Integer from 1 to 10000.

vector.numCandidates?:

number
= min(10000, 20 * vector.limit)
Vector search candidates. Integer from 1 to 10000. An explicit value is sent to MongoDB unchanged, which rejects a value below the resolved vector.limit.

vector.searchIndexName?:

string
Bring-your-own collections only. Search this existing vector index instead of the registered one. With this option, filters always use the `_id` pre-filter, so the index must declare _id as a filter field. It must also index the registered embedding field with the same embedding mode (vectors or autoEmbed); otherwise MongoDB rejects the query. Managed indexes throw an error.

text:

object
Full-text retrieval configuration, independent of vector retrieval.

text.query:

string
Non-empty full-text query.

text.paths:

string[]
Non-empty array of indexed source field paths for full-text matching.

text.searchIndexName?:

string
Bring-your-own collections only. Search this existing full-text index instead of the registered one. Managed indexes throw an error.

text.limit?:

number
= min(10000, max(4 * topK, 20))
Maximum text results contributed to fusion. Integer from 1 to 10000.

rerank?:

object
Enable native reranking after fusion. Omit for hybrid retrieval only. An empty object is invalid.

rerank.query:

string
Required when rerank is supplied. Non-empty relevance query, independent of both retrieval queries.

rerank.paths:

string[]
Required when rerank is supplied. Non-empty array of source fields used to judge relevance. MongoDB returns an error if any candidate document lacks a specified field.

rerank.model?:

string
= rerank-2.5
Native reranking model, independent of the embedding model. MongoDB determines model availability.

rerank.numDocsToRerank:

number
Required when rerank is supplied. Maximum fused documents to rerank and return before topK. Integer from 1 to 1000.

Returns QueryResult[] in final relevance order. score is the native reranking score when reranking is enabled, or the fusion score otherwise. These scores use different scales.

Invalid requests throw MastraError. Server failures preserve their causes, including unavailable reranking, unsupported models, and missing source fields. The method never silently substitutes a model or skips reranking.

describeIndex()
Direct link to describeindex

Returns information about the index (collection).

indexName:

string
Name of the collection to describe

Returns:

interface IndexStats {
dimension: number
count: number
metric?: 'cosine' | 'euclidean' | 'dotproduct'
}

On an autoEmbed index, dimension is read from the index definition and reports MongoDB's default of 1024 when the index doesn't pin one. metric is omitted when the autoEmbed index doesn't specify a similarity. count counts documents that carry the embedded text field, since the generated vectors aren't stored on your documents.

count is an exact count of the documents that carry the embedding field. On a large collection without a regular MongoDB index on that field, the count scans the collection, so avoid calling describeIndex() from request paths or health checks. upsert() and updateVector() read the dimension from the index definition and don't count documents.

deleteIndex()
Direct link to deleteindex

Deletes a vector index. Mastra records which search indexes and collections it created, and drops only those:

  • Managed index (created without collectionName): drops the collection and all its data. If a collection with that name already existed when createIndex() ran, Mastra keeps it and drops only the search indexes it created. Managed indexes created before @mastra/mongodb@1.15.0, or registered by 1.15 through 1.27 without an ownership record, aren't dropped until you call claimLegacyIndex() for them.
  • Bring-your-own index (created with collectionName): drops the vector and full-text indexes Mastra created. The collection and its documents are kept.

Mastra keeps any search index that existed before createIndex() or createSearchIndex() ran, that another logical index still uses, or that an earlier version registered. Drop those yourself if you no longer need them. Pointing an index at a different searchIndexName counts as a new index that Mastra doesn't own unless that call creates it. If Mastra created the old vector index, it keeps cleanup responsibility for it and drops it when the logical index is deleted. When one logical index is deleted and another registration still uses a search index, Mastra keeps that index and passes cleanup responsibility to the other registration. The last registration to be deleted drops it. Renaming a text index with createSearchIndex() keeps responsibility for the old index Mastra created, and Mastra drops it when the logical index is deleted, not at rename time.

deleteIndex() throws these errors:

  • NOT_REGISTERED: the name has no registration, and nothing is dropped. If the collection predates @mastra/mongodb@1.15.0, call claimLegacyIndex() first.
  • OWNERSHIP_UNKNOWN: a managed index registered by 1.15 through 1.27 has no ownership record. Call claimLegacyIndex() first.
  • IN_USE: another registration still uses the managed collection. Mastra checks this again when you retry a stalled delete.
  • CAPABILITY_CHECK_FAILED: the check for transaction support failed. Nothing changed, so retry.
  • OUTCOME_UNKNOWN: MongoDB couldn't confirm whether the delete committed. Retry. If the retry throws NOT_REGISTERED, the delete completed. A retry deletes whatever is registered under the name at that point, and no read can tell the original registration from a re-created one. If another process may re-create the index, coordinate with it before you retry. Don't retry by name if you can't rule out a re-create.

createIndex(), createSearchIndex() and claimLegacyIndex() throw INDEX_DELETING while a delete is half-finished, and while Mastra is still removing a search index it created under the same name (see cleanup errors and logs). Retrying deleteIndex() resumes and finishes a half-finished delete.

Concurrent deletes of indexes that share a collection are coordinated with transactions on Atlas, Atlas Local and replica sets. On a standalone server they aren't, and neither is a create that runs during a delete, so don't run them concurrently there. A createIndex() or createSearchIndex() call that starts using a search index a running deleteIndex() is about to drop throws INDEX_DELETING. Retry it once the delete finishes. Retrying is safe: if the delete already handed the search index to the new registration, that registration is kept and drops the index when it's deleted. A call throws CONFLICT and provisions nothing when, before its last check ahead of provisioning, deleteIndex() removes its registration or another call changes the registration's collection or the names of the search indexes the call is about to create. A createSearchIndex() call also throws CONFLICT when another call changed the registration after it was read. A createIndex() call on an existing registration throws CONFLICT and changes nothing when the registration was deleted or recreated after it was read. A registration created by an earlier version is the exception: the call re-reads it once and proceeds against the current registration. A deleteIndex() that overlaps another delete and a re-create leaves the new registration alone. A re-created managed collection has one exception, listed under cleanup limits.

Mastra records the Atlas ID of every search index it creates and drops or updates search indexes only by the ID it recorded, so a recorded index is never confused with one recreated under the same name. Cleanup limits lists the exceptions. Identical concurrent calls both succeed, and the index is recorded once. When the registration changes after that last check, or a deleteIndex() and a re-create with the same names overlap, the call throws CONFLICT. The index it created is still recorded: it's kept as a retired index that deleteIndex() drops, handed to the registration that now uses the name, or dropped. If a process crashes or stalls during a create or a cleanup, the next createIndex(), createSearchIndex(), deleteIndex() or claimLegacyIndex() on that collection finishes the work once 5 minutes have passed.

If createIndex() or createSearchIndex() fails before its search index is created, Mastra removes the registration that call inserted, or restores only the fields that call wrote. Mastra never undoes a search index it created. If createIndex() creates the vector index and then fails to create the companion full-text index, it throws and keeps the vector index registered, so a retry or deleteIndex() handles it.

Mastra reads and writes its registry (__mastra_vector_indexes__) and its internal provisioning journal (__mastra_vector_ops__) on the primary with majority read and write concerns, and commits its transactions the same way, whatever the client's read preference and concerns. This adds latency to these methods. These writes wait until the required number of the replica set's data-bearing voting members acknowledge them. In a primary-secondary-arbiter (PSA) replica set with its secondary down, the arbiter stores no data and can't acknowledge. The writes wait until the secondary is back. Don't modify __mastra_vector_ops__.

The BYO classification is recorded durably when the index is created, so it's applied correctly even by a different process (e.g. an index created by a setup job and later deleted by a long-lived service). Always pass the logical index name (the indexName used at createIndex), not the physical collection name.

indexName:

string
Logical name of the index to delete

Cleanup errors and logs
Direct link to Cleanup errors and logs

createIndex() and createSearchIndex() can throw these errors while search indexes are being created or removed. Each message is shown verbatim, with placeholders in angle brackets:

  • CONFLICT: search index "<name>" on "<collection>" is in status <status> (id <id>); the previous index under this name is still being removed. Retry. If it persists, drop it manually. Atlas still lists an earlier index under this name with status DELETING or DOES_NOT_EXIST, and Mastra doesn't create over it. A DELETING row usually clears within seconds. If the error persists, drop the row by ID as shown below. The error only delays the create. Nothing is dropped or lost while it lasts.
  • CONFLICT: Index "<indexName>" was removed or recreated by another call while this one ran, so nothing was provisioned. Retry.
  • CONFLICT: the target changed concurrently; the index this call created is kept as a retired index of the registration and removed by deleteIndex
  • CONFLICT: the registration was removed or recreated while this call ran; what it created was handed over or removed
  • INDEX_DELETING: search index "<name>" on "<collection>" is pending removal of an index Mastra created (cleanup record <_id>). Retry: retrying runs the cleanup. If the drop keeps failing, the block remains and the failure is logged at error level.
  • FAILED: The create of search index "<name>" on "<collection>" may or may not have reached Atlas. Retry.

Mastra also logs these messages:

  • warn: search index "<name>" on "<collection>" (id <id>) may have been created by Mastra; kept; drop it manually if unused. Mastra couldn't confirm whether its create reached Atlas, for example after a lost response or a crash, and an index with that name now exists. Mastra doesn't record it as its own, so deleteIndex() keeps it. The message can repeat when Mastra removes its internal record. If no logical index uses the search index, drop it by ID.
  • warn: search index "<name>" on "<collection>" (id <id>) is not recorded as created by Mastra: its id time <time> is more than 30 s before the pre-list at <time>. The index Atlas returned is older than Mastra's create, so Mastra treats it as created by someone else and keeps it.
  • error: could not drop search index "<name>" (id <id>) on "<collection>"; cleanup record <_id> keeps blocking the name: <error>. Mastra retries the drop, and logs this again if it fails, on each later createIndex(), createSearchIndex(), deleteIndex() or claimLegacyIndex() on that collection. Until the drop succeeds, calls that use that name throw INDEX_DELETING.

To drop a search index by ID in mongosh, list the collection's search indexes and pass the id of the one to drop:

db.getCollection('movies').getSearchIndexes()
db.runCommand({ dropSearchIndex: 'movies', id: '<id>' })
note

On Atlas Local, dropping a collection that still has search indexes can leave rows with status DOES_NOT_EXIST that reappear when a collection with the same name is created again. Mastra then throws the CONFLICT for a row that's still being removed, and retrying doesn't help. Drop the stuck row by ID with dropSearchIndex. To avoid it, drop a collection's search indexes before you drop the collection.

Cleanup limits
Direct link to Cleanup limits

  • Unconfirmed creates: if a create's response is lost, or the process crashes before Mastra records the new index, Mastra keeps the index and logs the may have been created by Mastra warning. In rarer cases, such as a process paused for more than 5 minutes in the middle of a create, the index is kept without a log. Drop it by ID if unused.
  • Indexes registered by earlier versions: these have no recorded ID, so Mastra lists the name when a delete starts, records the listed ID and drops by it. If someone drops and recreates the index under the same name before that listing, Mastra drops the recreated one. When another logical index still uses the name, Mastra transfers the index to it with the ID recorded from that listing. Search indexes that earlier versions created and left unregistered stay unrecorded. Drop them yourself.
  • Mixed versions: upgrade every instance before relying on these cleanup guarantees. Older instances drop search indexes by name and ignore the provisioning journal.
  • A delete overlapping a re-create of a managed index: right before dropping a managed collection, deleteIndex() checks that its delete is still the current one, but MongoDB can't drop a collection conditionally. If the delete stalls between that check and the drop while another call finishes the same delete and createIndex() creates the collection again, the stalled delete drops the new collection. Don't re-create a managed index while a delete of it may still be running.
  • A managed collection created concurrently with the same option: createIndex() creates a managed collection with validationLevel: 'off', so a collection another client creates between Mastra's existence check and its create with other options, defaults included, is adopted and kept. If the other client also uses validationLevel: 'off' and no other option, MongoDB reports success to both, Mastra records the collection as its own, and deleteIndex() drops it. Don't let other clients create collections with the names of managed indexes.
  • A retarget made by another process: each MongoDBVector instance caches the collection and search index an index resolves to. When another process points the index at a different search index with createIndex(), this instance keeps querying the previous one until it reads the registration again, for example after createIndex(), createSearchIndex() or deleteIndex() on that index, or in a new instance.
  • Indexes dropped outside Mastra during a delete: if someone drops a search index Mastra recorded and Mastra creates a new one under that name while a delete is deciding, the registration that takes the name over can keep the old ID. Its later delete then leaves the new index in place. Drop it by ID if unused.
  • Identical external creates on an Atlas cluster: if another client creates a search index with the same name and an identical definition within about one round trip before Mastra's own create, Atlas returns that index's ID to Mastra, Mastra records the index as its own, and deleteIndex() drops it. Only a definition that matches the one Mastra generates triggers this, so in practice the other client is another Mastra process. An index whose ID is more than 30 seconds older than Mastra's create is treated as someone else's and logged at warn. Mastra never drops a search index that another logical index uses, so only a client outside Mastra can lose an index this way. Atlas Local isn't affected.

claimLegacyIndex()
Direct link to claimlegacyindex

Records that Mastra created a managed index's collection and its recorded search indexes, so later calls to deleteIndex() and createSearchIndex() can manage them. Use it for managed indexes created before @mastra/mongodb@1.15.0, which have no registration, and for managed indexes registered by 1.15 through 1.27, which have no ownership record.

warning

After a claim, deleteIndex() drops the collection and all its data. A claim also overrides an explicit "not owned" record, such as a collection an earlier version adopted, so claim an index only when Mastra created the collection. The claim itself drops nothing.

await store.claimLegacyIndex({ indexName: 'movies' })

The claim records ownership before it verifies the search indexes, so a concurrent deleteIndex() can act on it before the claim completes. Don't delete an index while you claim it. If verification fails, Mastra attempts to undo the claim. A concurrent write to the registration makes that undo miss, and Mastra then logs a warn that the claim may still stand. After a failed claim, retry claimLegacyIndex() before calling deleteIndex().

Calling it again for a claimed index does nothing. It never overwrites another registration.

indexName:

string
Logical name of the managed index to claim

claimLegacyIndex() throws these errors:

  • BYO: the index is bring-your-own. Mastra keeps those collections, so there's nothing to claim.
  • CONFLICT: another registration already uses the name for something else, or a search index changed during the claim (index changed while it was being claimed; nothing was claimed; retry).
  • IN_USE: another registration uses the same collection.
  • NOT_FOUND: the name has no registration, and its collection or <name>_vector_index doesn't exist.
  • INDEX_DELETING: a delete of this index is half-finished. Retry deleteIndex().
  • FAILED: any other failure.

Upgrading from versions before this release
Direct link to Upgrading from versions before this release

Call claimLegacyIndex() once for each of these indexes:

  • Managed collections created before @mastra/mongodb@1.15.0, if you want to delete them with deleteIndex().
  • Managed indexes registered by 1.15 through 1.27 that you want to delete, or whose text mappings you want to change with createSearchIndex().

Indexes you only query, upsert into or list need no claim. Mastra refuses to delete or rewrite what it can't prove it created, so it asks you to confirm instead of guessing.

Upgrade every instance that shares the database before you rely on the cleanup guarantees in deleteIndex(). Older instances drop search indexes by name and ignore the provisioning journal. See cleanup limits for indexes that earlier versions created.

listIndexes()
Direct link to listindexes

Lists the logical Mastra index names (the indexName values passed to createIndex), not physical collection names. For a bring-your-own index whose data lives in an operational collection, the logical index name is returned instead of the physical collection name. The value can be passed straight back into describeIndex(), and into deleteIndex() for indexes Mastra has ownership records for. A legacy managed index needs claimLegacyIndex() first. Managed indexes created before durable metadata was introduced are still discovered via their ${name}_vector_index search index. The internal registry and provisioning journal collections are never listed.

Returns: Promise<string[]>

updateVector()
Direct link to updatevector

Update a single vector by ID or by metadata filter. Either id or filter must be provided, but not both.

Bring-your-own collections are read-only by default. upsert(), updateVector(), deleteVector(), and deleteVectors() throw a USER-category error on a BYO index unless it was created with the deprecated allowWrites: true option. See Indexing an existing collection.

indexName:

string
Name of the collection containing the vector

id?:

string
ID of the vector entry to update (mutually exclusive with filter)

filter?:

Record<string, any>
Metadata filter to identify vector(s) to update (mutually exclusive with id)

update:

object
Update data containing vector and/or metadata

update.vector?:

number[]
New vector data to update

update.metadata?:

Record<string, any>
New metadata to update

deleteVector()
Direct link to deletevector

Deletes a specific vector entry from an index by its ID.

indexName:

string
Name of the collection containing the vector

id:

string
ID of the vector entry to delete

deleteVectors()
Direct link to deletevectors

Delete multiple vectors by IDs or by metadata filter. Either ids or filter must be provided, but not both.

indexName:

string
Name of the collection containing the vectors to delete

ids?:

string[]
Array of vector IDs to delete (mutually exclusive with filter)

filter?:

Record<string, any>
Metadata filter to identify vectors to delete (mutually exclusive with ids)

disconnect()
Direct link to disconnect

Closes the MongoDB client connection. Should be called when done using the store.

Response types
Direct link to Response types

Query results are returned in this format:

interface QueryResult {
id: string
score: number
metadata?: Record<string, any>
vector?: number[] // Only included if includeVector is true
document?: string // Source text stored with the vector, when available
}

Error handling
Direct link to Error handling

The store throws typed errors that can be caught:

try {
await store.query({
indexName: 'my_collection',
queryVector: queryVector,
})
} catch (error) {
// Handle specific error cases
if (error.message.includes('Invalid collection name')) {
console.error(
'Collection name must start with a letter or underscore and contain only valid characters.',
)
} else if (error.message.includes('Collection not found')) {
console.error('The specified collection does not exist')
} else {
console.error('Vector store error:', error.message)
}
}

Automated embedding
Direct link to Automated embedding

MongoDB can generate the embeddings for you. Create the index with autoEmbed and a Voyage AI model, write plain text through documents, and search with queryText. No embedding provider runs in your application, and no vectors travel through it.

import { MongoDBVector } from '@mastra/mongodb'

const store = new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DB_NAME,
})

// No `dimension`: the embedding model determines it.
await store.createIndex({
indexName: 'movies',
autoEmbed: { model: 'voyage-4' },
filterFields: ['year'],
})

// Automated Embedding indexes build slower than client-embedded ones.
await store.waitForIndexReady({ indexName: 'movies', timeoutMs: 300000 })

// No `vectors`: MongoDB embeds the text as documents are written.
await store.upsert({
indexName: 'movies',
documents: [
'A lonely astronaut adrift near a strange ocean planet.',
'A heist crew robs a bank vault in Paris.',
],
metadata: [{ year: 1972 }, { year: 2001 }],
})

// No `queryVector`: MongoDB embeds the query string with the same model.
const results = await store.query({
indexName: 'movies',
queryText: 'space opera about isolation',
topK: 5,
filter: { year: { $gt: 1970 } },
})

autoEmbed options
Direct link to autoembed-options

model:

string
Voyage AI model to embed with, for example voyage-4. MongoDB rejects a name it does not support and lists the ones it does.

path?:

string
= document
Text field to embed. Defaults to the managed document field that upsert({ documents }) writes. Point it at a field of your own to index an existing collection in place.

similarity?:

'cosine' | 'dotProduct' | 'euclidean'
Vector similarity function. Defaults to MongoDB's own default when omitted.

numDimensions?:

number
= 1024
Length of the generated embeddings. Common values are 256, 512, 1024, and 2048.

quantization?:

'float' | 'scalar' | 'binary' | 'binaryNoRescore'
= scalar
Storage format for the generated vectors.

indexingMethod?:

'hnsw' | 'flat'
= hnsw
Index structure for the vector field.

hnswOptions?:

{ maxEdges?: number; numEdgeCandidates?: number }
Tuning for the HNSW graph. MongoDB's defaults suit most workloads.

Any other field the autoEmbed index definition accepts is forwarded to MongoDB as given, so options added after this release work without a package update. Anything omitted keeps MongoDB's default.

Important notes:

  • On MongoDB Atlas, Automated Embedding isn't a Preview feature, and the cluster needs storage auto-scaling enabled. On self-managed deployments it's a Preview feature that needs mongot configured with a Voyage AI API key. For local development, use the mongodb/mongodb-atlas-local:preview image.
  • The Voyage AI API key must be provisioned through the Atlas UI. A key issued directly by Voyage AI is rejected by the default embedding endpoint.
  • MongoDB stores the generated vectors outside your collection, so documents carry text only. includeVector: true isn't supported on an autoEmbed index and throws.
  • Embeddings are generated asynchronously. A query can legitimately return no results for a short time after a write, even once the index reports ready.
  • An index declares either a vector field or an autoEmbed field, never both. Omit autoEmbed to keep supplying your own vectors. The client-side path is unchanged.
  • Passing vectors to an autoEmbed index is an error, since they would be written to a field no index reads.
  • When document is the embedded field it's no longer a declared filter field, so documentFilter uses the $match pre-filter automatically. Metadata filters declared through filterFields still push into $vectorSearch.
  • updateVector() rejects a vector update on an autoEmbed index. Upsert the document with new text instead, and MongoDB re-embeds it.
  • queryVector still works against an autoEmbed index, but the vector must come from a compatible model and match the index quantization. MongoDB rejects a mismatch.
  • Embedding generation is billed per token, for both documents and queries.

Indexing an existing collection
Direct link to Indexing an existing collection

You can create a vector index on an existing operational collection instead of using a managed collection. This is useful when you want to add vector search capabilities to documents that already exist in your MongoDB database.

import { MongoDBVector } from '@mastra/mongodb'

const store = new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DB_NAME,
})

// Create a vector index on an existing 'transactions' collection
await store.createIndex({
indexName: 'precedents',
dimension: 1024,
collectionName: 'transactions', // Use existing collection
searchIndexName: 'txn_vec_idx', // Custom search index name
})

// Wait for the index to be ready
await store.waitForIndexReady({ indexName: 'precedents' })

// Query using document mode to get full source documents
const hits = await store.query({
indexName: 'precedents',
queryVector: embeddings,
topK: 5,
metadataMode: 'document', // Returns full document as metadata
})

// hits[0].metadata now contains all fields from the source document
console.log(hits[0].metadata.amount, hits[0].metadata.customField)

// Full-text / hybrid search on a BYO collection is opt-in: provision the text index first.
await store.createSearchIndex({ indexName: 'precedents', fields: ['note'] })

The diagram shows what MongoDBVector reads, writes, and drops in a bring-your-own setup.

MongoDBVector records each index in the mastra_vector_indexes registry, queries your collection&#39;s documents, creates and drops only the search indexes it created, and reuses search indexes that already existed without changing them. With Automated Embedding, document text is sent to Voyage AI.

Text version of the diagram

Important notes:

  • The collection must already exist and contain documents with an embedding field (or the custom embeddingFieldPath you configured)
  • The collection is never created or dropped when using collectionName
  • A BYO index is read-only. upsert(), updateVector(), deleteVector(), and deleteVectors() throw a clear error rather than mutating caller-owned operational documents. Write embeddings into the same documents from your application, or use autoEmbed and let MongoDB generate them. The deprecated allowWrites: true option still lets the store write. Entries written by older versions without the flag are treated as read-only (fail closed).
  • Use metadataMode: 'document' when querying to retrieve the full source document as metadata
  • In 'document' mode the embedding is omitted from metadata by default; pass includeVector: true to retain it (and also expose it as a top-level vector)
  • Filtering in 'document' mode operates on root document fields, not a nested metadata. subdocument. filter: { lane: 'fraud' } matches the top-level lane field of your operational documents (in the default 'field' mode, bare fields are rewritten to metadata.<field> for managed collections). Both the pushdown and $match fallback paths honor this.
  • Native ObjectId _ids are supported. Operational collections commonly key on ObjectId; query results coerce _id to a string (the QueryResult.id contract), and deleteVector()/updateVector()/deleteVectors() accept that string and match the underlying ObjectId document. Managed collections (string _ids) are unaffected.
  • Full-text and hybrid search on a BYO collection are opt-in: no full-text index is auto-created, so call createSearchIndex() before textQuery()/hybridQuery(). The full-text index builds asynchronously. Call waitForSearchIndexReady() (or pass waitUntilReady: true) before an immediate text/hybrid query.
  • deleteIndex() on a BYO index drops the vector and text indexes Mastra created but preserves the collection, its documents, and any search index that existed before
  • To filter in 'document' mode without loading candidate _ids, declare the root fields you filter on: createIndex({ ..., filterFields: ['lane'] })
warning

allowWrites is deprecated and will be removed in the next major version. With allowWrites: true, deleteVector() and deleteVectors() delete your original documents, not only their embeddings, and upsert() replaces each document's metadata field. The setting is stored with the index, so it applies to every process that uses that index name.

allowWrites is a guard in Mastra, not database access control. It doesn't limit the MongoDB user, and it doesn't stop createIndex(), createSearchIndex(), or deleteIndex() from managing search indexes and the __mastra_vector_indexes__ registry. To enforce read-only access, connect with a MongoDB role that can only read the collection, and use a separate user to create indexes.

Best practices
Direct link to Best practices

  • Index metadata fields used in filters for optimal query performance.
  • Use consistent field naming in metadata to avoid unexpected query results.
  • Monitor index and collection statistics to ensure efficient search.
  • When indexing existing collections, ensure all documents have the required embedding field.

Usage example
Direct link to Usage example

Vector embeddings with MongoDB
Direct link to vector-embeddings-with-mongodb

Embeddings are numeric vectors used by memory's semanticRecall to retrieve related messages by meaning (not keywords).

note

MongoDB Vector Search is recommended for production use. For self-hosted deployments, Vector Search is available with local Atlas deployments via the Atlas CLI.

This setup uses FastEmbed, a local embedding model, to generate vector embeddings. To use this, install @mastra/fastembed:

npm install @mastra/fastembed@latest

Add the following to your agent:

src/mastra/agents/example-mongodb-agent.ts
import { Memory } from '@mastra/memory'
import { Agent } from '@mastra/core/agent'
import { MongoDBStore, MongoDBVector } from '@mastra/mongodb'
import { fastembed } from '@mastra/fastembed'

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-6.1-sol',
memory: new Memory({
storage: new MongoDBStore({
id: 'mongodb-storage',
uri: process.env.MONGODB_URI!,
dbName: process.env.MONGODB_DB_NAME!,
}),
vector: new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI!,
dbName: process.env.MONGODB_DB_NAME!,
}),
embedder: fastembed,
options: {
lastMessages: 10,
semanticRecall: {
topK: 3,
messageRange: 2,
},
generateTitle: true, // generates descriptive thread titles automatically
},
}),
})

Vector embeddings with VoyageAI
Direct link to Vector embeddings with VoyageAI

VoyageAI provides specialized embedding models optimized for retrieval tasks. VoyageAI is also integrated with MongoDB Atlas for multimodal embeddings.

npm install @mastra/voyageai@latest

Basic usage example:

src/mastra/agents/example-mongodb-voyageai-agent.ts
import { Memory } from '@mastra/memory'
import { Agent } from '@mastra/core/agent'
import { MongoDBStore, MongoDBVector } from '@mastra/mongodb'
import { voyage } from '@mastra/voyageai'

export const mongodbVoyageAgent = new Agent({
id: 'mongodb-voyage-agent',
name: 'MongoDB VoyageAI Agent',
instructions: 'You are an AI agent with semantic recall powered by VoyageAI and MongoDB.',
model: 'openai/gpt-6.1-sol',
memory: new Memory({
storage: new MongoDBStore({
id: 'mongodb-storage',
uri: process.env.MONGODB_URI!,
dbName: process.env.MONGODB_DB_NAME!,
}),
vector: new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI!,
dbName: process.env.MONGODB_DB_NAME!,
}),
embedder: voyage, // VoyageAI's default model (voyage-3.5, 1024 dimensions)
options: {
lastMessages: 10,
semanticRecall: {
topK: 5,
messageRange: 2,
},
},
}),
})

For detailed VoyageAI embedding examples including specialized models, multimodal embeddings, and retrieval optimization, see the VoyageAI embeddings documentation.