stores/mongodb/README.md
MongoDB Atlas Search implementation for Mastra, providing vector similarity search and index management using MongoDB Atlas Local or Atlas Cloud.
npm install @mastra/mongodb
import { MongoDBVector } from '@mastra/mongodb';
const vectorDB = new MongoDBVector({
id: 'mongodb-vector',
uri: 'mongodb://mongodb:mongodb@localhost:27018/?authSource=admin&directConnection=true',
dbName: 'vector_db',
});
// Connect to MongoDB
await vectorDB.connect();
// Create a new vector index (collection)
await vectorDB.createIndex({
indexName: 'my_vectors',
dimension: 1536,
metric: 'cosine', // or 'euclidean', 'dotproduct'
});
// Upsert vectors
const ids = await vectorDB.upsert({
indexName: 'my_vectors',
vectors: [[0.1, 0.2, ...], [0.3, 0.4, ...]],
metadata: [{ text: 'doc1' }, { text: 'doc2' }],
});
// Query vectors
const results = await vectorDB.query({
indexName: 'my_vectors',
queryVector: [0.1, 0.2, ...],
topK: 10,
filter: { text: 'doc1' },
includeVector: false,
minScore: 0.5,
});
// Clean up
await vectorDB.disconnect();
import { MongoDBStore } from '@mastra/mongodb';
const store = new MongoDBStore({
id: 'mongodb-store',
uri: 'mongodb://mongodb:mongodb@localhost:27018/?authSource=admin&directConnection=true',
dbName: 'mastra',
});
// Create a thread
await store.saveThread({
thread: {
id: 'thread-123',
resourceId: 'resource-456',
title: 'My Thread',
metadata: { key: 'value' },
createdAt: new Date(),
},
});
// Add messages to thread
await store.saveMessages({
messages: [
{
id: 'msg-789',
threadId: 'thread-123',
role: 'user',
content: { content: 'Hello' },
resourceId: 'resource-456',
createdAt: new Date(),
},
],
});
// Query threads and messages
const savedThread = await store.getThreadById({ threadId: 'thread-123' });
const { messages } = await store.listMessages({ threadId: 'thread-123' });
The MongoDB vector store is initialized with:
id: Unique identifier for this store instanceuri: MongoDB connection string (with credentials and options)dbName: Name of the database to useembeddingFieldPath (optional): Path to the field that stores vector embeddings. Supports nested paths using dot notation (e.g., 'text.contentEmbedding'). Defaults to 'embedding'.Example:
const vectorDB = new MongoDBVector({
id: 'mongodb-vector',
uri: 'mongodb://mongodb:mongodb@localhost:27018/?authSource=admin&directConnection=true',
dbName: 'vector_db',
});
If you need to store embeddings in a nested field structure, use the embeddingFieldPath option:
const vectorDB = new MongoDBVector({
id: 'mongodb-vector',
uri: 'mongodb://mongodb:mongodb@localhost:27018/?authSource=admin&directConnection=true',
dbName: 'vector_db',
embeddingFieldPath: 'text.contentEmbedding', // Store embeddings at text.contentEmbedding
});
$eq, $ne, $gt, $gte, $lt, $lte$and, $or$in, $nin$regex, $likeExample filter:
{
$and: [{ age: { $gt: 25 } }, { tags: { $in: ['tag1', 'tag2'] } }];
}
The following distance metrics are supported:
cosine → Cosine similarity (default)euclidean → Euclidean distancedotproduct → Dot productcreateIndex({indexName, dimension, metric}): Create a new collection with vector search supportupsert({indexName, vectors, metadata?, ids?}): Add or update vectorsquery({indexName, queryVector, topK?, filter?, includeVector?, minScore?, documentFilter?}): Search for similar vectors (optionally filter by document content)Note:
documentFilterallows filtering results based on the content of thedocumentfield. Example:{ $contains: 'specific text' }will return only vectors whose associated document contains the specified text.
updateVector({ indexName, id?, filter?, update }): Update a single vector by ID or metadata filterdeleteVector({ indexName, id }): Delete a single vector by IDdeleteVectors({ indexName, ids?, filter? }): Delete multiple vectors by IDs or metadata filterlistIndexes(): List all vector-enabled collectionsdescribeIndex(indexName): Get collection statistics (dimension, count, metric)deleteIndex(indexName): Delete a collectiondisconnect(): Close the MongoDB connectionsaveThread({ thread }): Create or update a threadgetThreadById({ threadId }): Get a thread by IDdeleteThread({ threadId }): Delete a thread and its messagessaveMessages({ messages }): Save multiple messages in a transactionlistMessages({ threadId, perPage?, page? }): Get messages for a thread with paginationdeleteMessages(messageIds): Delete specific messagesEach query result includes:
id: Vector IDscore: Similarity score (higher is more similar)metadata: Associated metadatavector: Original vector (if includeVector is true)Integration tests use MongoDB Atlas Local via Docker. See docker-compose.yml for setup. The test suite includes readiness checks for Atlas Search before running vector operations.