mongodb-developer
researched 2026-05-28T18:47:35.618Z· 0 sources · 0 concepts · skill mongodb-developer
This local skill is generated from docs/mongodb-developer-context.md in 10gen/mdb-tam.
MongoDB Developer Context
- This local skill is generated from docs/mongodb-developer-context.md in 10gen/mdb-tam. [source]
When to use this skill
- Use this skill when the user needs help with: [source]
- Writing code using any MongoDB official driver (Node.js, Python, Java, Go, C#, Rust, PHP, Ruby, Kotlin, Scala, C, C++) [source]
- Connection string construction, pooling configuration, and topology events [source]
- Error handling, retry logic, and resilient application patterns [source]
- Multi-document transactions and causal consistency [source]
- Bulk write operations, ordered and unordered [source]
- Aggregation pipelines from driver code [source]
- Change streams from driver code [source]
- GridFS file storage and retrieval [source]
- mongosh commands, scripting, and automation [source]
- Atlas CLI automation [source]
- MongoDB error codes and their resolutions [source]
- Atlas Admin API calls [source]
- Atlas MCP server tools [source]
- Schema design, index strategy, aggregation patterns [source]
- Antipatterns and common failure modes [source]
- Customer troubleshooting (slow queries, connection issues, auth failures, replica set elections) [source]
- Start from the bundled context below, and defer to the cited official documentation for exact APIs, commands, and edge-case behavior. [source]
Skill guidance
- Treat docs/mongodb-developer-context.md as the source document for this skill. [source]
- Prefer the workflows, checklists, and patterns captured in the bundled context before improvising. [source]
- Cross-reference with mongodb-expert skill for general MQL/aggregation depth. [source]
- Cross-reference with mongodb-atlas-expert skill for Atlas-specific operational depth. [source]
- Cross-reference with mongodb-performance-troubleshooting skill for deep performance analysis. [source]
- Cross-reference with mongodb-schema-design skill for data modeling patterns. [source]
- Cross-reference with mongodb-data-lifecycle skill for change streams and TTL details. [source]
- Cross-reference with mongodb-encryption skill for CSFLE and Queryable Encryption. [source]
- If the request is outside this topic, choose a more appropriate skill instead of forcing this one. [source]
SRV Connection String (Atlas and DNS seedlist)
- SRV records provide automatic host discovery and TLS defaults. Atlas always provides SRV URIs. The driver resolves DNS SRV and TXT records to discover all mongos/replica set members. [source]
Connection String Best Practices
- Always set appName so ops teams can trace connections in server logs. [source]
- Use SRV connection strings for Atlas and any DNS-seedlist deployment. [source]
- Never hard-code credentials; use environment variables or a secrets manager. [source]
- Set compressors=zstd for bandwidth-sensitive workloads (requires server and driver support). [source]
- For serverless functions (Lambda, Cloud Functions), set maxPoolSize=1 and maxIdleTimeMS=10000 to avoid connection exhaustion. [source]
- Set retryWrites=true&retryReads=true explicitly in shared URIs for clarity (both are default since 4.2). [source]
How Pools Work
- Each MongoClient maintains a pool of TCP connections per server (per replica set member or mongos). When your application requests an operation, the driver checks out a connection from the pool, executes the operation, and returns the connection. [source]
The Golden Rule: One Client Per Application
- Create a single MongoClient instance and share it across your application. The client is thread-safe (or goroutine-safe, or async-safe) in every official driver. Opening a new client per request is the most common pooling antipattern. [source]
Pool Monitoring Events
- All drivers emit connection pool events for observability: [source]
- connectionPoolCreated / connectionPoolClosed [source]
- connectionCreated / connectionClosed [source]
- connectionCheckedOut / connectionCheckedIn [source]
- connectionCheckOutFailed / connectionCheckOutStarted [source]
- connectionPoolCleared [source]
- Subscribe to these events to track pool saturation, connection churn, and wait-queue depth. [source]
3.1 Node.js (mongodb package)
3.2 Python (PyMongo)
3.3 Java (mongodb-driver-sync / mongodb-driver-reactivestreams)
3.4 Go (go.mongodb.org/mongo-driver v2)
- Installation: go get go.mongodb.org/mongo-driver/v2/mongo [source]
3.5 C# (.NET Driver)
- NuGet: MongoDB.Driver [source]
Retryable Writes
- Enabled by default since MongoDB 4.2. The driver automatically retries eligible write operations exactly once after a transient network error or a failover. [source]
- Eligible operations: insertOne, updateOne, replaceOne, deleteOne, findOneAndUpdate, findOneAndReplace, findOneAndDelete, insertMany (ordered or unordered), bulkWrite (ordered or unordered). [source]
- updateMany, deleteMany (not idempotent at the protocol level) [source]
- Writes with w: 0 (unacknowledged) [source]
- Individual writes within an explicit transaction (the transaction itself is retried) [source]
- RetryableWriteError - the driver retries automatically [source]
- NoWritesPerformed (MongoDB 6.1+) - both attempts failed without writing; safe to retry at app layer [source]
- TransientTransactionError - retry the entire transaction [source]
- UnknownTransactionCommitResult - retry commitTransaction() [source]
Retryable Reads
Error Handling Strategy Checklist
- Let the driver handle retryable errors (retryWrites/retryReads). [source]
- Catch DuplicateKeyError (11000) for idempotent upserts. [source]
- Catch ServerSelectionTimeoutError for connectivity failures and alert. [source]
- Catch WriteConcernError when w: majority cannot be satisfied. [source]
- Catch MaxTimeMSExpired (50) and investigate slow queries. [source]
- Wrap bulk operations to inspect BulkWriteError.writeErrors array. [source]
- Log error codes, not just messages, for searchability. [source]
- Never swallow errors silently; always log or propagate. [source]
When to Use
- Use transactions when business logic requires atomic updates across multiple documents or collections. [source]
- Prefer single-document atomicity when possible; redesign schemas before reaching for transactions. [source]
- Transactions are supported on replica sets (4.0+) and sharded clusters (4.2+). [source]
Transaction Retry Pattern
Transaction Anti-Patterns
- Transactions lasting >5 seconds (increases WiredTiger cache pressure and conflict risk). [source]
- Modifying >1,000 documents in a single transaction. [source]
- Using transactions for single-document operations (unnecessary overhead). [source]
- Not using withTransaction() helper (loses automatic retry logic). [source]
- Running DDL inside transactions (createCollection, createIndex). [source]
- Relying on transactions instead of redesigning schema for single-document atomicity. [source]
Client-Level Bulk Write (MongoDB 8.0+)
- MongoDB 8.0 introduced client-level bulkWrite() that can write to multiple collections and databases in a single network round-trip: [source]
Bulk Operation Best Practices
- Use unordered for maximum throughput when order does not matter. [source]
- Batch sizes: the driver auto-batches into 100,000-operation groups. For very large imports, chunk at the application level. [source]
- Catch BulkWriteError and inspect writeErrors to identify which operations failed. [source]
- Use upsert: true in UpdateOne/ReplaceOne models for idempotent loads. [source]
- For multi-million-row imports, use mongoimport or mongorestore instead of driver bulk writes. [source]
Running Pipelines
- All drivers support collection.aggregate(pipeline, options). Key options: [source]
Aggregation Best Practices
- Place $match and $project as early as possible to reduce documents flowing through the pipeline. [source]
- Use $match before $lookup to limit the join scope. [source]
- Set allowDiskUse: true only when necessary (large groupings/sorts). [source]
- Use maxTimeMS to prevent runaway pipelines. [source]
- Use $merge or $out for materialized views, not in-app aggregation. [source]
- Use explain('executionStats') to verify index utilization in $match stages. [source]
Change Stream Best Practices
- Always persist resume tokens - store in a separate collection or external store for crash recovery. [source]
- Use fullDocument: 'updateLookup' when you need the complete document after an update. [source]
- Use fullDocumentBeforeChange: 'whenAvailable' (6.0+) for audit trails. [source]
- Filter early with $match in the pipeline to reduce network traffic. [source]
- Handle invalidate events (dropped collection, renamed collection) by reopening the stream. [source]
- For cross-collection CDC, watch at the database level: db.watch(). [source]
- For cluster-wide events, watch at the client level: client.watch(). [source]
When to Use
How GridFS Works
GridFS Best Practices
- Use GridFS only for files >16 MB. For smaller files, store as BinData in documents. [source]
- Set appropriate chunkSizeBytes - smaller chunks for random-access reads, larger for sequential streaming. [source]
- Index fs.files on fields you query (e.g., metadata.author, filename). [source]
- Use streaming APIs (not readAll) to avoid loading entire files into memory. [source]
- Consider Atlas Data Lake or S3 for very large-scale file storage; GridFS is not a CDN replacement. [source]
mongosh Best Practices
- Use --file for repeatable scripts, not interactive copy-paste. [source]
- Use --quiet in CI/CD to suppress the mongosh banner. [source]
- Use printjson() for structured output; print() for plain text. [source]
- Store maintenance scripts in version control alongside application code. [source]
- Use --eval for one-liners in shell scripts and cron jobs. [source]
- mongosh supports full ES2022+: use async/await, destructuring, for...of, and template literals. [source]
- Use .mongoshrc.js for custom prompts, helpers, and default config. [source]
14. Resilient Application Checklist
- Use this checklist when reviewing any application that connects to MongoDB: [source]
- [ ] Single client instance shared across the application [source]
- [ ] Connection string uses SRV format for Atlas / DNS seedlist deployments [source]
- [ ] appName set for observability [source]
- [ ] retryWrites and retryReads enabled (default since 4.2) [source]
- [ ] Write concern set to majority for durability [source]
- [ ] Read preference matches the use case (primary for consistency, secondary for read scale) [source]
- [ ] maxPoolSize right-sized for deployment environment [source]
- [ ] serverSelectionTimeoutMS set to a reasonable value (not infinite) [source]
- [ ] Graceful shutdown closes the client [source]
- [ ] Error handling catches specific error types, not generic exceptions [source]
- [ ] Duplicate key errors handled for idempotent operations [source]
- [ ] Transactions use withTransaction() helper with automatic retry [source]
- [ ] Projections used to limit returned fields [source]
- [ ] Indexes cover query patterns (ESR rule) [source]
- [ ] maxTimeMS set on long-running queries and aggregations [source]
- [ ] Change stream resume tokens persisted for crash recovery [source]
- [ ] Monitoring events wired to observability stack (pool events, command events, SDAM events) [source]
Official Driver Documentation
Connection and Pooling
Retryable Operations
Transactions
GridFS
mongosh
Specifications
Children
- No children recorded.