🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@mastra/mongodb

Package Overview
Dependencies
Maintainers
1
Versions
751
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install
Package version was removed
This package version has been unpublished, mostly likely due to security reasons
This package has malicious versions linked to the ongoing "Mastra AI framework compromise" supply chain attack.

Affected versions:

1.9.3
View campaign page

@mastra/mongodb

MongoDB provider for Mastra - includes vector store capabilities

unpublished
Source
npmnpm
Version
1.9.3
Version published
Weekly downloads
27K
-6.82%
Maintainers
1
Weekly downloads
 
Created
Source

@mastra/mongodb

MongoDB Atlas Search implementation for Mastra, providing vector similarity search and index management using MongoDB Atlas Local or Atlas Cloud.

Installation

npm install @mastra/mongodb

Prerequisites

  • MongoDB Atlas Local (via Docker) or MongoDB Atlas Cloud instance with Atlas Search enabled
  • MongoDB 7.0+ recommended

Usage

Vector Store

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,
});

// Clean up
await vectorDB.disconnect();

Storage

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' });

Configuration

The MongoDB vector store is initialized with:

  • id: Unique identifier for this store instance
  • uri: MongoDB connection string (with credentials and options)
  • dbName: Name of the database to use
  • embeddingFieldPath (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',
});

Custom Embedding Field Path

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

Features

Vector Store Features

  • Vector similarity search with cosine, euclidean, and dotproduct metrics (Atlas Search)
  • Metadata filtering with MongoDB-style query syntax
  • Automatic UUID generation for vectors
  • Collection (index) management: create, list, describe, delete
  • Atlas Search readiness checks for reliable testing

Storage Features

  • Thread and message storage with JSON support
  • Efficient batch operations
  • Rich metadata support
  • Timestamp tracking

Supported Filter Operators

  • Comparison: $eq, $ne, $gt, $gte, $lt, $lte
  • Logical: $and, $or
  • Array: $in, $nin
  • Text: $regex, $like

Example filter:

{
  $and: [{ age: { $gt: 25 } }, { tags: { $in: ['tag1', 'tag2'] } }];
}

Distance Metrics

The following distance metrics are supported:

  • cosine → Cosine similarity (default)
  • euclidean → Euclidean distance
  • dotproduct → Dot product

Vector Store Methods

  • createIndex({indexName, dimension, metric}): Create a new collection with vector search support
  • upsert({indexName, vectors, metadata?, ids?}): Add or update vectors
  • query({indexName, queryVector, topK?, filter?, includeVector?, documentFilter?}): Search for similar vectors (optionally filter by document content)

Note: documentFilter allows filtering results based on the content of the document field. 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 filter
  • deleteVector({ indexName, id }): Delete a single vector by ID
  • deleteVectors({ indexName, ids?, filter? }): Delete multiple vectors by IDs or metadata filter
  • listIndexes(): List all vector-enabled collections
  • describeIndex(indexName): Get collection statistics (dimension, count, metric)
  • deleteIndex(indexName): Delete a collection
  • disconnect(): Close the MongoDB connection

Storage Methods

  • saveThread({ thread }): Create or update a thread
  • getThreadById({ threadId }): Get a thread by ID
  • deleteThread({ threadId }): Delete a thread and its messages
  • saveMessages({ messages }): Save multiple messages in a transaction
  • listMessages({ threadId, perPage?, page? }): Get messages for a thread with pagination
  • deleteMessages(messageIds): Delete specific messages

Query Response Format

Each query result includes:

  • id: Vector ID
  • score: Similarity score (higher is more similar)
  • metadata: Associated metadata
  • vector: Original vector (if includeVector is true)

Testing

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.

  • MongoDB Atlas Search Documentation
  • MongoDB Node.js Driver

FAQs

Package last updated on 17 Jun 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts