> ## Documentation Index
> Fetch the complete documentation index at: https://agno-v2.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
./cookbook/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

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

**1. Install dependencies**

```bash theme={null}
uv pip install -U agno ddgs openai pymongo
```

**2. Export your OpenAI API key**

```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"
```

**3. 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
```

**4. Run the example**

Save the code above as `async_mongodb_for_agent.py`, then run:

```bash theme={null}
python async_mongodb_for_agent.py
```

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


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.