> ## Documentation Index
> Fetch the complete documentation index at: https://docs.agentium.in/llms.txt
> Use this file to discover all available pages before exploring further.

# MongoDB Storage

> MongoDBStorage driver for document-based persistence. Requires mongodb. Call initialize() before use.

# MongoDB Storage

**MongoDBStorage** stores key-value data in MongoDB collections. It requires the `mongodb` package and is ideal for teams already using MongoDB or for document-oriented workloads at scale.

***

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install mongodb
  ```

  ```bash pnpm theme={null}
  pnpm add mongodb
  ```

  ```bash yarn theme={null}
  yarn add mongodb
  ```
</CodeGroup>

***

## Setup

<Steps>
  <Step title="Install mongodb">
    Add the `mongodb` package to your project.
  </Step>

  <Step title="Create storage instance">
    Pass URI and optional database/collection names.
  </Step>

  <Step title="Call initialize()">
    Connects to MongoDB and creates a unique index on `(namespace, key)`. **Required** before use.
  </Step>
</Steps>

```typescript theme={null}
import { MongoDBStorage } from "@agentium/core";

const storage = new MongoDBStorage(
  process.env.MONGO_URI ?? "mongodb://localhost:27017",
  "myapp",      // dbName (default: "agentium")
  "kv_store"    // collectionName (default: "kv_store")
);

await storage.initialize(); // Required!

await storage.set("users", "prefs-123", { theme: "dark" });
const prefs = await storage.get("users", "prefs-123");
```

***

## Constructor

<ParamField path="uri" type="string" required>
  MongoDB connection URI. Example: `mongodb://localhost:27017` or `mongodb+srv://user:pass@cluster.mongodb.net/`
</ParamField>

<ParamField path="dbName" type="string" required={false} default="agentium">
  Database name.
</ParamField>

<ParamField path="collectionName" type="string" required={false} default="kv_store">
  Collection name for key-value documents.
</ParamField>

```typescript theme={null}
// Minimal
const storage = new MongoDBStorage("mongodb://localhost:27017");

// Full
const storage = new MongoDBStorage(
  "mongodb+srv://user:pass@cluster.mongodb.net/",
  "production_db",
  "agent_data"
);
```

***

## Full Example

```typescript theme={null}
import { Agent, Memory, MongoDBStorage, openai } from "@agentium/core";

const storage = new MongoDBStorage(
  process.env.MONGO_URI!,
  "myapp",
  "agent_data"
);
await storage.initialize();

const memory = new Memory({
  storage,
  maxShortTermMessages: 50,
  enableLongTerm: true,
});

const agent = new Agent({
  name: "Assistant",
  model: openai("gpt-4o"),
  storage,
  memory,
});

await agent.run("Remember my preferences.", { sessionId: "user-abc" });
```

***

## Document Shape

Each stored document has the form:

```json theme={null}
{
  "namespace": "memory:short",
  "key": "session-123",
  "value": { "messages": [...] },
  "updatedAt": "2025-02-26T12:00:00.000Z"
}
```

A unique index on `(namespace, key)` ensures fast lookups and prevents duplicates.

***

## Atlas & Replica Sets

MongoDBStorage works seamlessly with all MongoDB deployment types:

### MongoDB Atlas (Cloud)

```typescript theme={null}
const storage = new MongoDBStorage(
  "mongodb+srv://user:pass@cluster0.abc123.mongodb.net/",
  "production",
  "agent_data"
);
await storage.initialize();
```

Atlas features like auto-scaling, backups, and global clusters work transparently — MongoDBStorage uses the standard MongoDB driver.

### Replica Sets

For self-hosted replica sets, include all members in the connection string:

```typescript theme={null}
const storage = new MongoDBStorage(
  "mongodb://host1:27017,host2:27017,host3:27017/?replicaSet=rs0",
  "agentium"
);
```

Reads are directed to the primary by default. For read-heavy workloads, the MongoDB driver can be configured with read preferences.

### Sharded Clusters

MongoDBStorage works with sharded clusters via `mongos` routers. For optimal performance, shard the `kv_store` collection on the `namespace` field:

```bash theme={null}
sh.shardCollection("agentium.kv_store", { namespace: 1 })
```

### Best Practices

* Use `mongodb+srv://` connection strings for Atlas (handles DNS-based discovery)
* Enable SSL/TLS for production connections
* Set `retryWrites=true` in the connection string for automatic retry on transient errors
* Use a dedicated database for Agentium data to simplify backup and access control

***

## API Reference

| Method                          | Description                                                           |
| ------------------------------- | --------------------------------------------------------------------- |
| `initialize()`                  | Connects to MongoDB and creates index. **Must be called** before use. |
| `get<T>(namespace, key)`        | Get value. Returns `null` if not found.                               |
| `set<T>(namespace, key, value)` | Store value (upsert).                                                 |
| `delete(namespace, key)`        | Remove document.                                                      |
| `list<T>(namespace, prefix?)`   | List keys. Prefix uses regex `^prefix`.                               |
| `close()`                       | Closes the MongoDB client connection.                                 |
