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
create_state_store("async_mongodb", ...) — see Async MongoDB (motor).
Method reference
Bothmongodb 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 nativeasync_* method for use inside an event loop:
Request flow
A typical FastAPI request reads and writes session state through the async store without blocking the loop.Best Practices
Anchor key patterns with a fixed prefix
Anchor key patterns with a fixed prefix
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.Pair with a conversation backend
Pair with a conversation backend
Use
database_url for chat history and state_url for fast agent state — MongoDB handles state only.Set TTL for ephemeral data
Set TTL for ephemeral data
Pass
ttl on set() for session-scoped preferences that should expire automatically.Use replica sets in production
Use replica sets in production
Append
replicaSet= to the URL for high availability.Choose collection names per app
Choose collection names per app
Set
collection="prod_state" vs collection="staging_state" to isolate environments on one cluster.Related
Redis State Store
In-memory state for sub-millisecond access
Database Persistence
Overview of conversation and state backends

