MongoDB vector store
The MongoDBVector class provides vector search using MongoDB Atlas Vector Search. It enables efficient similarity search and metadata filtering within your MongoDB collections.
InstallationDirect link to Installation
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/mongodb@latest
pnpm add @mastra/mongodb@latest
yarn add @mastra/mongodb@latest
bun add @mastra/mongodb@latest
Usage exampleDirect 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 PathDirect 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 optionsDirect link to Constructor options
id:
uri:
dbName:
options?:
embeddingFieldPath?:
MethodsDirect 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.
indexName:
dimension:
metric?:
filterFields?:
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.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:
timeoutMs?:
checkIntervalMs?:
upsert()Direct link to upsert
Adds or updates vectors and their metadata in the collection.
indexName:
vectors:
metadata?:
ids?:
documents?:
query()Direct link to query
Searches for similar vectors with optional metadata filtering.
indexName:
queryVector:
topK?:
filter?:
metadata field)documentFilter?:
includeVector?:
numCandidates?:
describeIndex()Direct link to describeindex
Returns information about the index (collection).
indexName:
Returns:
interface IndexStats {
dimension: number
count: number
metric: 'cosine' | 'euclidean' | 'dotproduct'
}
deleteIndex()Direct link to deleteindex
Deletes a collection and all its data.
indexName:
listIndexes()Direct link to listindexes
Lists all vector collections in the MongoDB database.
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.
indexName:
id?:
filter?:
update:
update.vector?:
update.metadata?:
deleteVector()Direct link to deletevector
Deletes a specific vector entry from an index by its ID.
indexName:
id:
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:
ids?:
filter?:
disconnect()Direct link to disconnect
Closes the MongoDB client connection. Should be called when done using the store.
Response typesDirect 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
}
Error handlingDirect 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)
}
}
Best practicesDirect 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.
- Regularly monitor index and collection statistics to ensure efficient search.
Usage exampleDirect link to Usage example
Vector embeddings with MongoDBDirect link to vector-embeddings-with-mongodb
Embeddings are numeric vectors used by memory's semanticRecall to retrieve related messages by meaning (not keywords).
MongoDB Atlas 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
- pnpm
- Yarn
- Bun
npm install @mastra/fastembed@latest
pnpm add @mastra/fastembed@latest
yarn add @mastra/fastembed@latest
bun add @mastra/fastembed@latest
Add the following to your agent:
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-5.5',
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 VoyageAIDirect 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
- pnpm
- Yarn
- Bun
npm install @mastra/voyageai@latest
pnpm add @mastra/voyageai@latest
yarn add @mastra/voyageai@latest
bun add @mastra/voyageai@latest
Basic usage example:
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-5.5',
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 comprehensive VoyageAI embedding examples including specialized models, multimodal embeddings, and retrieval optimization, see the VoyageAI embeddings documentation.