Skip to main content

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


Setup

1

Install mongodb

Add the mongodb package to your project.
2

Create storage instance

Pass URI and optional database/collection names.
3

Call initialize()

Connects to MongoDB and creates a unique index on (namespace, key). Required before use.

Constructor

string
required
MongoDB connection URI. Example: mongodb://localhost:27017 or mongodb+srv://user:pass@cluster.mongodb.net/
string
default:"agentium"
Database name.
string
default:"kv_store"
Collection name for key-value documents.

Full Example


Document Shape

Each stored document has the form:
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)

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:
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:

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