mongo-conventionslisted
Install: claude install-skill eric-sabe/engsys
# MongoDB Conventions
Applies to: any code touching MongoDB in this repo (storage layers, ingest scripts, transforms, API routes).
> Naturalize: confirm the driver, database name, and the system-of-record collection(s) in `CLAUDE.md`.
## Async access (Motor)
- Use the **async driver (Motor)** end-to-end in async services; `await` every DB call. Don't block the event loop with the sync `pymongo` client in request paths.
- The sync `pymongo` client is acceptable only for things Motor doesn't cover (e.g. GridFS) or for offline scripts — keep it off the hot path.
- Centralize connection setup: build the connection string from the environment (`MONGODB_URI` / `DATABASE_URL`, falling back to a local default), and detect localhost to skip TLS for dev.
- Create collections and indexes idempotently in an `initialize_collections()`-style routine: check `list_collection_names()` first, then `create_index(...)`. Mark uniqueness explicitly (`unique=True`) on natural keys (e.g. `content_id`).
- Guard in-memory caches (vector indexes, derived state) with an `asyncio.Lock` so concurrent requests don't rebuild them simultaneously.
```python
from motor.motor_asyncio import AsyncIOMotorClient, AsyncIOMotorDatabase
client: AsyncIOMotorClient = AsyncIOMotorClient(connection_string)
db: AsyncIOMotorDatabase = client[db_name]
await client.admin.command("ping") # verify connectivity
await db.content_raw.create_index("content_id", unique=True)
docs = await db.content_chunks.count_docum