# PyMongo + Atlas

```python
from pymongo import MongoClient
from pymongo.server_api import ServerApi
import os

client = MongoClient(
    os.environ["MONGODB_URI"],
    serverSelectionTimeoutMS=5000,
    maxPoolSize=20,
    server_api=ServerApi("1"),
)
# prove it at startup
client.admin.command("ping")
```

## Rules

- One `MongoClient` per process. It is thread-safe and owns the pool. Creating a client per request is the classic way to exhaust connections.
- The client connects lazily: the first real operation triggers server selection. The startup `ping` forces that early so config errors surface before traffic.
- `serverSelectionTimeoutMS=5000` keeps a bad network path from hanging for 30 seconds.
- On old Linux distros or minimal containers, TLS verification can fail with certificate errors. Fix it with the system CA bundle (`tlsCAFile` pointing at your CA certs), never by disabling TLS. Atlas requires TLS.
- Passwords with special characters (`@`, `/`, `:`) must be URL-encoded in the URI, or auth fails with a confusing error. Encode just the password, not the whole string.

## Verify

Run the `ping` from the deploy environment. Success means the URI, user, password, and IP access list entry are all correct.