Skip to Content
ReferenceRAGReference: MongoDB Vector Store | Vector Databases | RAG | Mastra Docs

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:

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 (see naming rules below)

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[]>

updateIndexById()

Updates a specific vector entry by its ID with new vector data and/or metadata.

indexName:

string
Name of the collection containing the vector

id:

string
ID of the vector entry to update

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

deleteIndexById()

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

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.