Skip to main content
MongoDB stores agent state as flexible documents — ideal for nested metadata and schema-less data.
from praisonaiagents import Agent, db

agent = Agent(
    name="DocumentBot",
    instructions="You are a helpful assistant.",
    db=db(state_url="mongodb://localhost:27017/praisonai"),
    session_id="mongo-session",
)
agent.start("Store my preferences in MongoDB state")
The user sets preferences; MongoDB stores flexible agent state as documents.

Quick Start

1

Simple Usage

pip install pymongo praisonai
from praisonaiagents import Agent, db

agent = Agent(
    name="DocumentBot",
    db=db(state_url="mongodb://localhost:27017/praisonai"),
    session_id="session-1",
)
agent.start("Hello!")
2

With Configuration

Use MongoDBStateStore directly for collection and database control:
from praisonai.persistence import create_state_store

store = create_state_store(
    "mongodb",
    url="mongodb://localhost:27017",
    database="praisonai",
    collection="agent_state",
)
store.set("user:123:prefs", {"theme": "dark"}, ttl=3600)

How It Works

MongoDB is a state store — it holds key-value agent state, not full conversation history. Pair it with a SQL conversation backend when you need both.
FeatureDescription
Document storageNested objects and arrays without a fixed schema
TTL indexAutomatic expiry via expires_at field
Hash operationshget, hset, hgetall for structured state

Configuration Options

OptionTypeDefaultDescription
urlstr"mongodb://localhost:27017"MongoDB connection URL
databasestr"praisonai"Database name
collectionstr"state"Collection for state documents

URL formats

db(state_url="mongodb://localhost:27017/praisonai")
db(state_url="mongodb://user:pass@host:27017/praisonai?replicaSet=rs0")
For async workloads, use create_state_store("async_mongodb", ...).

Best Practices

Use database_url for chat history and state_url for fast agent state — MongoDB handles state only.
Pass ttl on set() for session-scoped preferences that should expire automatically.
Append replicaSet= to the URL for high availability.
Set collection="prod_state" vs collection="staging_state" to isolate environments on one cluster.

Redis State Store

In-memory state for sub-millisecond access

Database Persistence

Overview of conversation and state backends