MongoDB for Agent

Use MongoDb as the database for an agent.

"""Use MongoDb as the database for an agent.

Run `uv pip install openai pymongo` 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
```
"""

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

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

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

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

Run the Example

Create and activate a virtual environment, then install the dependencies:

uv venv --python 3.12
source .venv/bin/activate
uv pip install -U agno pymongo ddgs openai

Set OPENAI_API_KEY in your environment. Start MongoDB with the credentials used by the example:

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

Save the Python code as mongodb_for_agent.py and run:

python mongodb_for_agent.py