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

# MongoDB State Store

> Flexible document storage for agent state with TTL and rich metadata

MongoDB stores agent state as flexible documents — ideal for nested metadata and schema-less data.

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    Agent[🤖 Agent] --> Store[🍃 MongoDB State]
    Store --> Collection[📄 state collection]
    Collection --> DB[(MongoDB)]

    classDef agent fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef store fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef database fill:#10B981,stroke:#7C90A0,color:#fff

    class Agent agent
    class Store store
    class Collection,DB database
```

## Quick Start

<Steps>
  <Step title="Simple Usage">
    ```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    pip install pymongo praisonai
    ```

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonaiagents import Agent, db

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

  <Step title="With Configuration">
    Use `MongoDBStateStore` directly for collection and database control:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    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)
    ```
  </Step>
</Steps>

***

## 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.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant Agent
    participant Store as MongoDBStateStore
    participant MongoDB

    Agent->>Store: set(key, value, ttl?)
    Store->>MongoDB: upsert document
    Agent->>Store: get(key)
    MongoDB-->>Agent: value
```

| Feature              | Description                                      |
| -------------------- | ------------------------------------------------ |
| **Document storage** | Nested objects and arrays without a fixed schema |
| **TTL index**        | Automatic expiry via `expires_at` field          |
| **Hash operations**  | `hget`, `hset`, `hgetall` for structured state   |

***

## Configuration Options

| Option       | Type  | Default                       | Description                    |
| ------------ | ----- | ----------------------------- | ------------------------------ |
| `url`        | `str` | `"mongodb://localhost:27017"` | MongoDB connection URL         |
| `database`   | `str` | `"praisonai"`                 | Database name                  |
| `collection` | `str` | `"state"`                     | Collection for state documents |

### URL formats

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
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

<AccordionGroup>
  <Accordion title="Pair with a conversation backend">
    Use `database_url` for chat history and `state_url` for fast agent state — MongoDB handles state only.
  </Accordion>

  <Accordion title="Set TTL for ephemeral data">
    Pass `ttl` on `set()` for session-scoped preferences that should expire automatically.
  </Accordion>

  <Accordion title="Use replica sets in production">
    Append `replicaSet=` to the URL for high availability.
  </Accordion>

  <Accordion title="Choose collection names per app">
    Set `collection="prod_state"` vs `collection="staging_state"` to isolate environments on one cluster.
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Redis State Store" icon="cubes-stacked" href="/docs/features/persistence-redis">
    In-memory state for sub-millisecond access
  </Card>

  <Card title="Database Persistence" icon="database" href="/docs/features/persistence">
    Overview of conversation and state backends
  </Card>
</CardGroup>
