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

# Use AsyncMongoDb as the database for an agent

> Persist agent sessions in MongoDB with AsyncMongoDb and async run methods.

````python async_mongodb_for_agent.py theme={null}
"""Use AsyncMongoDb as the database for an agent.

Run `uv pip install openai pymongo motor` to install dependencies

Run a local MongoDB server using:
```bash
docker run -d \
  --name local-mongo \
  -p 27017:27017 \
  -e MONGO_INITDB_ROOT_USERNAME=mongoadmin \
  -e MONGO_INITDB_ROOT_PASSWORD=secret \
  mongo
```
or use our script:
```bash
./scripts/run_mongodb.sh
```
"""

import asyncio

from agno.agent import Agent
from agno.db.mongo import AsyncMongoDb
from agno.tools.websearch import WebSearchTools

# ---------------------------------------------------------------------------
# Setup
# ---------------------------------------------------------------------------
db_url = "mongodb://mongoadmin:secret@localhost:27017"
db = AsyncMongoDb(db_url=db_url)

# ---------------------------------------------------------------------------
# Create Agent
# ---------------------------------------------------------------------------
agent = Agent(
    db=db,
    tools=[WebSearchTools()],
    add_history_to_context=True,
)

# ---------------------------------------------------------------------------
# Run Agent
# ---------------------------------------------------------------------------
if __name__ == "__main__":
    asyncio.run(agent.aprint_response("How many people live in Canada?"))
    asyncio.run(agent.aprint_response("What is their national anthem called?"))
````

## Run the Example

<Steps>
  <Snippet file="create-venv-step.mdx" />

  <Step title="Install dependencies">
    ```bash theme={null}
    uv pip install -U agno ddgs openai pymongo
    ```
  </Step>

  <Step title="Export your OpenAI API key">
    <CodeGroup>
      ```bash Mac/Linux theme={null}
      export OPENAI_API_KEY="your_openai_api_key_here"
      ```

      ```bash Windows theme={null}
      $Env:OPENAI_API_KEY="your_openai_api_key_here"
      ```
    </CodeGroup>
  </Step>

  <Step title="Run MongoDB">
    ```bash theme={null}
    docker run -d -p 27017:27017 --name mongodb -e MONGO_INITDB_ROOT_USERNAME=mongoadmin -e MONGO_INITDB_ROOT_PASSWORD=secret mongo:latest
    ```
  </Step>

  <Step title="Run the example">
    Save the code above as `async_mongodb_for_agent.py`, then run:

    ```bash theme={null}
    python async_mongodb_for_agent.py
    ```
  </Step>
</Steps>

Full source: [cookbook/06\_storage/mongo/async\_mongo/async\_mongodb\_for\_agent.py](https://github.com/agno-agi/agno/blob/main/cookbook/06_storage/mongo/async_mongo/async_mongodb_for_agent.py)
