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

# Async MongoDB for Agent

> Store agent sessions and run history asynchronously in MongoDB with AsyncMongoDb.

`AsyncMongoDb` stores an Agent's sessions and run history asynchronously in MongoDB. Use async Agent methods such as `arun()` and `aprint_response()`.

## Usage

Provide either `db_url` or `db_client`. This example uses `db_url`.

Install the `pymongo` (4.9 or later), `openai`, and `ddgs` packages:

```shell theme={null}
uv pip install "pymongo>=4.9" openai ddgs
```

<Note>
  `motor` clients are also supported, but `motor` is deprecated. Use PyMongo's async client instead.
</Note>

### Run MongoDB

Install [Docker Desktop](https://docs.docker.com/get-started/get-docker/), then start MongoDB on port `27017`:

```bash theme={null}
docker run -d \
  --name local-mongo \
  -p 27017:27017 \
  -e MONGO_INITDB_ROOT_USERNAME=mongoadmin \
  -e MONGO_INITDB_ROOT_PASSWORD=secret \
  mongo
```

```python async_mongodb_for_agent.py theme={null}
import asyncio

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

db_url = "mongodb://mongoadmin:secret@localhost:27017"

db = AsyncMongoDb(db_url=db_url)

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


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())
```

## Parameters

<Snippet file="db-async-mongodb-params.mdx" />
