Skip to main content

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@beta

Usage Example

import { MongoDBVector } from "@mastra/mongodb";

const store = new MongoDBVector({
id: 'mongodb-vector',
url: process.env.MONGODB_URL,
database: process.env.MONGODB_DATABASE,
});

Constructor Options

id:

string
Unique identifier for this vector store instance

url:

string
MongoDB connection string (URI)

database:

string
Name of the MongoDB database to use

options?:

MongoClientOptions
Optional MongoDB client options

Methods

createIndex()

Creates a new vector index (collection) in MongoDB.

indexName:

string
Name of the collection to create

dimension:

number
Vector dimension (must match your embedding model)

metric?:

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

upsert()

Adds or updates vectors and their metadata in the collection.

indexName:

string
Name of the collection to insert into

vectors:

number[][]
Array of embedding vectors

metadata?:

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

ids?:

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

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

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

minScore?:

number
= 0
Minimum similarity score threshold

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";
}

deleteIndex()

Deletes a collection and all its data.

indexName:

string
Name of the collection to delete

listIndexes()

Lists all vector collections in the MongoDB database.

Returns: Promise<string[]>

updateVector()

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

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()

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()

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()

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.