Use AsyncMongoDb as the database for an agent

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

async_mongodb_for_agent.py
"""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?"))

Keep both turns in one event loop

Replace the saved script's two asyncio.run(...) calls with this entry point. The MongoDB client is reused by both turns and closed before its event loop exits:

Run both MongoDB turns
async def main():
    try:
        await agent.aprint_response("How many people live in Canada?")
        await agent.aprint_response("What is their national anthem called?")
    finally:
        await db.close()


if __name__ == "__main__":
    asyncio.run(main())

Run the Example

Set up your virtual environment

uv venv --python 3.12
source .venv/bin/activate

Install dependencies

uv pip install -U agno ddgs openai pymongo

Export your OpenAI API key

export OPENAI_API_KEY="your_openai_api_key_here"

Run MongoDB

docker run -d -p 27017:27017 --name mongodb -e MONGO_INITDB_ROOT_USERNAME=mongoadmin -e MONGO_INITDB_ROOT_PASSWORD=secret mongo:latest

Run the example

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

python async_mongodb_for_agent.py

Full source: cookbook/06_storage/mongo/async_mongo/async_mongodb_for_agent.py