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_DATABASE,
})
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_DATABASE,
embeddingFieldPath: 'text.contentEmbedding', // Store embeddings at text.contentEmbedding
})
Constructor optionsDirect link to Constructor options
id:
uri:
dbName:
options?:
embeddingFieldPath?:
MethodsDirect link to Methods
createIndex()Direct link to createindex
Creates a new vector index (collection) in MongoDB.
indexName:
dimension:
metric?:
upsert()Direct link to upsert
Adds or updates vectors and their metadata in the collection.
indexName:
vectors:
metadata?:
ids?:
query()Direct link to query
Searches for similar vectors with optional metadata filtering.
indexName:
queryVector:
topK?:
filter?:
documentFilter?:
includeVector?:
minScore?:
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).
You must use a deployment hosted on MongoDB Atlas to successfully use the MongoDB Vector database.
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.4',
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
},
}),
})