Skip to main content
MongoDB stores agent state as flexible documents — ideal for nested metadata and schema-less data.
The user sets preferences; MongoDB stores flexible agent state as documents.

Quick Start

1

Simple Usage

2

With Configuration

Use MongoDBStateStore directly for collection and database control:

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.
MongoDBStateStore.keys(pattern) treats pattern as a glob, where * matches any run of characters and ? matches a single one. Anchor a known prefix explicitly — keys("session:*") — rather than passing raw user input, so a listing returns only the keys you expect.

Configuration Options

URL formats

For async workloads, use create_state_store("async_mongodb", ...) — see Async MongoDB (motor).

Method reference

Both mongodb and async_mongodb implement the full StateStore contract. Every method has an async_* twin that runs natively on the event loop; the sync method is a wrapper safe to call from any context.
hset stores fields as opaque top-level keys, so a dotted field like "a.b" round-trips through hget / hgetall verbatim rather than being reinterpreted as a nested MongoDB path.
hdel returns the number of fields actually present and removed, matching the StateStore contract and the Firestore / DynamoDB backends. Deleting a mix of present and absent fields reports only the real deletions.

Async MongoDB (motor)

The async backend (async_mongodb) uses motor for non-blocking I/O — pick it inside FastAPI, async handlers, or any live event loop.

Sync or async?

Agent with an async store

Create the async store, then pass it to the agent’s memory config:

Direct store usage

Every operation has a native async_* method for use inside an event loop:
Every async_* method has a sync wrapper of the same name without the prefix (store.get, store.keys, store.hset, …). The wrappers route through the async bridge, so they are safe from sync scripts, worker threads, and code running inside a live event loop.

Request flow

A typical FastAPI request reads and writes session state through the async store without blocking the loop.

Best Practices

Call keys("session:*") with a known prefix rather than passing raw user input into the glob, so a listing returns only the keys you intend to match.
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