Skip to main content

MongoDB 存储

🌐 MongoDB Storage

MongoDB 存储实现提供了一种可扩展的存储解决方案,使用 MongoDB 数据库,并支持文档存储和向量操作。

🌐 The MongoDB storage implementation provides a scalable storage solution using MongoDB databases with support for both document storage and vector operations.

安装
Direct link to 安装

🌐 Installation

npm install @mastra/mongodb@latest

用法
Direct link to 用法

🌐 Usage

确保你拥有一个本地 MongoDB Atlas(通过 Docker)或启用了 Atlas Search 的 MongoDB Atlas 云实例。建议使用 MongoDB 7.0 及以上版本。

🌐 Ensure you have a MongoDB Atlas Local (via Docker) or MongoDB Atlas Cloud instance with Atlas Search enabled. MongoDB 7.0+ is recommended.

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

const storage = new MongoDBStore({
id: 'mongodb-storage',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DATABASE,
});

参数
Direct link to 参数

🌐 Parameters

id:

string
Unique identifier for this storage instance.

uri:

string
MongoDB connection string (e.g., mongodb+srv://user:password@cluster.mongodb.net)

url?:

string
Deprecated. Use uri instead. MongoDB connection string (supported for backward compatibility).

dbName:

string
The name of the database you want the storage to use.

options?:

MongoClientOptions
MongoDB client options for advanced configuration (SSL, connection pooling, etc.).
Deprecation Notice

The url parameter is deprecated but still supported for backward compatibility. Please use uri instead in all new code.

构造函数示例
Direct link to 构造函数示例

🌐 Constructor Examples

你可以通过以下方式实例化 MongoDBStore

🌐 You can instantiate MongoDBStore in the following ways:

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

// Basic connection without custom options
const store1 = new MongoDBStore({
id: 'mongodb-storage-01',
uri: "mongodb+srv://user:password@cluster.mongodb.net",
dbName: "mastra_storage",
});

// Using connection string with options
const store2 = new MongoDBStore({
id: 'mongodb-storage-02',
uri: "mongodb+srv://user:password@cluster.mongodb.net",
dbName: "mastra_storage",
options: {
retryWrites: true,
maxPoolSize: 10,
serverSelectionTimeoutMS: 5000,
socketTimeoutMS: 45000,
},
});

附加说明
Direct link to 附加说明

🌐 Additional Notes

收藏管理
Direct link to 收藏管理

🌐 Collection Management

存储实现会自动处理集合的创建和管理。它会创建以下集合:

🌐 The storage implementation handles collection creation and management automatically. It creates the following collections:

  • mastra_workflow_snapshot:存储工作流状态和执行数据
  • mastra_evals:存储评估结果和元数据
  • mastra_threads:存储对话线程
  • mastra_messages:存储单条消息
  • mastra_traces:存储遥测和跟踪数据
  • mastra_scorers:存储评分和评估数据
  • mastra_resources:存储资源工作内存数据

初始化
Direct link to 初始化

🌐 Initialization

当你将存储传递给 Mastra 类时,init() 会在任何存储操作之前自动调用:

🌐 When you pass storage to the Mastra class, init() is called automatically before any storage operation:

import { Mastra } from "@mastra/core";
import { MongoDBStore } from "@mastra/mongodb";

const storage = new MongoDBStore({
id: 'mongodb-storage',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DATABASE,
});

const mastra = new Mastra({
storage, // init() is called automatically
});

如果你直接使用存储而不通过 Mastra,你必须显式调用 init() 来创建集合:

🌐 If you're using storage directly without Mastra, you must call init() explicitly to create the collections:

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

const storage = new MongoDBStore({
id: 'mongodb-storage',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DATABASE,
});

// Required when using storage directly
await storage.init();

// Access domain-specific stores via getStore()
const memoryStore = await storage.getStore('memory');
const thread = await memoryStore?.getThreadById({ threadId: "..." });
warning

如果未调用 init(),集合将不会被创建,存储操作可能会静默失败或抛出错误。

向量搜索功能
Direct link to 向量搜索功能

🌐 Vector Search Capabilities

MongoDB 存储包括用于人工智能应用的内置向量搜索功能:

🌐 MongoDB storage includes built-in vector search capabilities for AI applications:

向量索引创建
Direct link to 向量索引创建

🌐 Vector Index Creation

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

const vectorStore = new MongoDBVector({
id: 'mongodb-vector',
uri: process.env.MONGODB_URI,
dbName: process.env.MONGODB_DATABASE,
});

// Create a vector index for embeddings
await vectorStore.createIndex({
indexName: "document_embeddings",
dimension: 1536,
});

向量运算
Direct link to 向量运算

🌐 Vector Operations

// Store vectors with metadata
await vectorStore.upsert({
indexName: "document_embeddings",
vectors: [
{
id: "doc-1",
values: [0.1, 0.2, 0.3, ...], // 1536-dimensional vector
metadata: {
title: "Document Title",
category: "technical",
source: "api-docs",
},
},
],
});

// Similarity search
const results = await vectorStore.query({
indexName: "document_embeddings",
vector: queryEmbedding,
topK: 5,
filter: {
category: "technical",
},
});

使用示例
Direct link to 使用示例

🌐 Usage Example

为代理添加内存
Direct link to 为代理添加内存

🌐 Adding memory to an agent

要向代理添加 MongoDB 内存,请使用 Memory 类并使用 MongoDBStore 创建一个新的 storage 键。该配置支持本地和远程 MongoDB 实例。

🌐 To add MongoDB memory to an agent use the Memory class and create a new storage key using MongoDBStore. The configuration supports both local and remote MongoDB instances.

src/mastra/agents/example-mongodb-agent.ts
import { Memory } from "@mastra/memory";
import { Agent } from "@mastra/core/agent";
import { MongoDBStore } from "@mastra/mongodb";

export const mongodbAgent = new Agent({
id: "mongodb-agent",
name: "mongodb-agent",
instructions:
"You are an AI agent with the ability to automatically recall memories from previous interactions.",
model: "openai/gpt-5.1",
memory: new Memory({
storage: new MongoDBStore({
uri: process.env.MONGODB_URI!,
dbName: process.env.MONGODB_DB_NAME!,
}),
options: {
generateTitle: true,
},
}),
});

使用代理
Direct link to 使用代理

🌐 Using the agent

使用 memoryOptions 来限定此请求的回忆范围。设置 lastMessages: 5 以限制基于最近性的回忆,使用 semanticRecall 获取最相关的 topK: 3 条消息,包括每个匹配消息周围的 messageRange: 2 条邻近消息以提供上下文。

🌐 Use memoryOptions to scope recall for this request. Set lastMessages: 5 to limit recency-based recall, and use semanticRecall to fetch the topK: 3 most relevant messages, including messageRange: 2 neighboring messages for context around each match.

src/test-mongodb-agent.ts
import "dotenv/config";

import { mastra } from "./mastra";

const threadId = "123";
const resourceId = "user-456";

const agent = mastra.getAgent("mongodbAgent");

const message = await agent.stream("My name is Mastra", {
memory: {
thread: threadId,
resource: resourceId,
},
});

await message.textStream.pipeTo(new WritableStream());

const stream = await agent.stream("What's my name?", {
memory: {
thread: threadId,
resource: resourceId,
},
memoryOptions: {
lastMessages: 5,
semanticRecall: {
topK: 3,
messageRange: 2,
},
},
});

for await (const chunk of stream.textStream) {
process.stdout.write(chunk);
}