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.
Installation
npm install @mastra/mongodb
Usage Example
import { MongoDBVector } from '@mastra/mongodb';
const store = new MongoDBVector({
url: process.env.MONGODB_URL,
database: process.env.MONGODB_DATABASE,
});
Constructor Options
url:
database:
options?:
Methods
createIndex()
Creates a new vector index (collection) in MongoDB.
indexName:
dimension:
metric?:
upsert()
Adds or updates vectors and their metadata in the collection.
indexName:
vectors:
metadata?:
ids?:
query()
Searches for similar vectors with optional metadata filtering.
indexName:
queryVector:
topK?:
filter?:
documentFilter?:
includeVector?:
minScore?:
describeIndex()
Returns information about the index (collection).
indexName:
Returns:
interface IndexStats {
dimension: number;
count: number;
metric: "cosine" | "euclidean" | "dotproduct";
}
deleteIndex()
Deletes a collection and all its data.
indexName:
listIndexes()
Lists all vector collections in the MongoDB database.
Returns: Promise<string[]>
updateIndexById()
Updates a specific vector entry by its ID with new vector data and/or metadata.
indexName:
id:
update:
update.vector?:
update.metadata?:
deleteIndexById()
Deletes a specific vector entry from an index by its ID.
indexName:
id:
disconnect()
Closes the MongoDB client connection. Should be called when done using the store.
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 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 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.