Skip to main content

MongoDBMemory

NoSQL document storage with flexible schema design and MongoDB-specific features.

Import

import { MongoDBMemory } from '@ag-kit/agents/storage';

Constructor

constructor(config: MongoDBMemoryConfig)

Configuration

config
MongoDBMemoryConfig
required
Configuration for MongoDB memory storage extending BaseMemory options

Basic Usage

// Simple MongoDB connection
const memory = new MongoDBMemory({
  connectionString: 'mongodb://localhost:27017',
  databaseName: 'agkit_memory',
  sessionId: 'user-session-123',
  enableContextManagement: true
});

// Add and retrieve events with flexible schema
await memory.add({
  message: {
    id: 'msg-1',
    role: 'user',
    content: 'Hello, I need help with my project',
    timestamp: new Date(),
    // MongoDB allows flexible document structures
    metadata: {
      platform: 'web',
      userAgent: 'Mozilla/5.0...',
      location: { lat: 40.7128, lng: -74.0060 }
    }
  },
  state: { 
    userId: 'user-123',
    tags: ['help', 'project'],
    // Any custom application data
    customData: {
      projectId: 'proj-456',
      workspaceId: 'ws-789'
    }
  }
});

const events = await memory.list({ limit: 10, maxTokens: 4000 });

Core Interface Methods

MongoDBMemory inherits from BaseMemory and implements all standard memory interface methods. For complete API documentation including list(), add(), addList(), delete(), retrieve(), clear(), getCount(), isEmpty(), and branching methods, see the BaseMemory API Reference.

Auto-Connection Setup

// MongoDBMemory handles connection automatically
const memory = new MongoDBMemory({
  connectionString: 'mongodb://username:password@localhost:27017',
  databaseName: 'agkit_memory',
  clientOptions: {
    maxPoolSize: 20,
    serverSelectionTimeoutMS: 5000,
    retryWrites: true
  }
});

// Or use existing connection
import { MongoClient } from 'mongodb';
const client = new MongoClient('mongodb://localhost:27017');
await client.connect();
const db = client.db('agkit_memory');

const memory2 = new MongoDBMemory({
  db,
  sessionId: 'user-session-789'
});

Unique Features

  • Auto-Connection Setup: No manual client creation required
  • Flexible Schema: Document-based storage with dynamic schema
  • No Predefined Structure: Adapt to changing requirements without migrations
  • JSON-Native: Natural handling of complex nested data structures
  • Horizontal Scaling: Built-in support for MongoDB sharding and replication

Limitations

  • Eventual Consistency: In distributed setups, reads may not immediately reflect writes
  • Memory Usage: Large documents can consume significant memory
  • Complex Joins: Limited support for complex relational operations
  • Learning Curve: Requires understanding of MongoDB concepts and query language