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 install @mastra/mongodb
Usage ExampleDirect link to Usage Example
import { MongoDBVector } from "@mastra/mongodb";
const store = new MongoDBVector({
url: process.env.MONGODB_URL,
database: process.env.MONGODB_DATABASE,
});
Constructor OptionsDirect link to Constructor Options
url:
database:
options?:
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()
Updates a specific vector entry by its ID with new vector data and/or metadata.
indexName:
id:
update:
update.vector?:
update.metadata?:
deleteVector()Direct link to deleteVector()
Deletes a specific vector entry from an index by its ID.
indexName:
id:
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.