api-database-mongodb
MongoDB Native Driver Patterns
Quick Guide: Talk to MongoDB through the official
mongodbdriver with no schema layer in between. Create ONEMongoClientper process and reuse it -- it owns the connection pool. Type collections with a generic:db.collection<UserDoc>("users"). Write operations return acknowledgements, never documents.find()returns a lazy cursor; stream it withfor awaitinstead oftoArray()for anything unbounded. Put$matchfirst in every pipeline so it can use an index. Verify indexes withexplain("executionStats")rather than assuming. Transactions need a replica set, a session on every operation, and a callback that can safely run twice.
<critical_requirements>
CRITICAL: Before Using This Skill
All code must follow project conventions in CLAUDE.md (kebab-case, named exports, import ordering,
import type, named constants)
(You MUST create exactly ONE MongoClient per process and reuse it -- the client owns a connection pool, so constructing one per request opens a new pool per request and exhausts the server's connection limit)
(You MUST pass { session } to EVERY operation inside a transaction -- an operation without it silently runs outside the transaction and is not rolled back)
(You MUST write withTransaction callbacks to be safely re-runnable -- the driver retries them on transient errors, so any side effect outside the transaction happens more than once)
(You MUST iterate or close every cursor you open -- an abandoned cursor holds server-side resources until it times out)