MongoDB¶
Scope: designing, securing and running MongoDB for applications, self-managed (Community and Enterprise) or on MongoDB Atlas (Atlas Core and Atlas Infinite clusters, and the Free and Flex tiers). The guidelines cover MongoDB 9.0, the current major version, and 8.0 and 7.0, which are supported until October 2029 and August 2027. Architecture-level data rules, such as data ownership, consistency between services and backups, are in general/data.md (DATA-1, DATA-5, DATA-8), and validating input, service identities and TLS in general/security.md (SEC-5, SEC-10, SEC-13). Driver code also follows Node.js or Python, and connecting from serverless functions is covered in Serverless and edge hosting. For a relational system of record, see PostgreSQL; for caching, Redis and caching; and for a document database that clients call directly, Firebase.
Entries are sorted by score from 1 to 10 (criteria): 9–10 start here or strongly recommended, 6–8 recommended, 1–5 further reading or conditional.
Adopted references¶
- 9 MongoDB Database Manual (MongoDB docs): the baseline. Read the manual for the version you run; the chapters on data modeling, indexes, transactions, replication, security and production notes matter most for application work.
- 8 Data Modeling in MongoDB and its best practices (MongoDB docs): the baseline for schema design: modeling for the application's access patterns, embedding or referencing, duplicated data, schema validation and indexes.
- 8 Atlas Architecture Center (MongoDB docs): the baseline for Atlas: recommended configurations for security, network access, authentication, backups, disaster recovery, high availability and monitoring, organized by the pillars of the Atlas Well-Architected Framework.
- 8 Security Checklist for Self-Managed Deployments (MongoDB docs): access control, role-based access, TLS, encryption, network exposure, auditing and secure configuration options.
- 8 Development Checklist (MongoDB docs): data durability, schema design, replication, sharding and driver settings to get right before production.
- 7 Schema Design Patterns (MongoDB docs): computed values, grouping data, polymorphic data, schema versioning, archiving and the single-collection pattern.
- 7 Schema Design Anti-Patterns (MongoDB docs): unbounded arrays, too many collections, unnecessary indexes, bloated documents and too many
$lookupoperations, and how to find them. - 7 Production Notes for Self-Managed Deployments (MongoDB docs): platforms, storage, networking, hardware and operating-system settings for running
mongodin production. - 7 Operations Checklist for Self-Managed Deployments (MongoDB docs): file systems, replication, journaling, hardware, operating-system settings, backups and monitoring.
- 7 MongoDB Atlas Operational Readiness Checklist (MongoDB docs): a checklist for setting up Atlas organizations, network security, backups, maintenance and monitoring before going live.
- 7 Indexing Strategies (MongoDB docs): mapping queries to indexes, the ESR guideline, sorting with indexes, selectivity, and unique indexes with schema validation.
Key rules¶
Data modeling¶
- 8
MONGO-1Design each collection from the application's read and write patterns: embed data that is read or updated together, and reference data that grows without bound, has many items on the child side, is written at different times or exists on its own. MongoDB's core modeling principle is that data accessed together is stored together. A write to one document is atomic, so embedding also removes the need for most multi-document transactions. (MongoDB, Data Modeling, Best Practices: link related data, Best Practices: atomicity) - 8
MONGO-2Keep documents bounded: cap arrays with the subset pattern or move their items to a separate collection, and move fields that aren't read together into separate documents. An unbounded array can exceed the 16 MiB document limit and slows down its indexes, and indexed arrays perform best with fewer than 1,000 elements. Large documents fill the RAM that the working set needs. Store files over the limit with GridFS. (MongoDB, Avoid Unbounded Arrays, Bloated Documents, Limits: BSON documents, Development Checklist: schema design) - 7
MONGO-3When the shape of a document changes, add aschemaVersionfield, and make the code's queries and updates handle every version that can still be in the collection. The schema versioning pattern keeps old and new documents side by side and avoids large migrations; a field stored in different places in different versions may need an index for each place. (MongoDB, Maintain Different Schema Versions) - 7
MONGO-4Once a collection's schema is established, add a$jsonSchemavalidator and keep the default behavior, which rejects invalid inserts and updates. The database then enforces types and allowed values for every client that writes, in addition to validating input at the trust boundary (SEC-10). (MongoDB, Schema Validation, Specify JSON Schema Validation, Best Practices: enforce schema with validation rules)
Indexes and queries¶
- 7
MONGO-5Create an index for every frequent query, order compound index keys by the ESR guideline (equality, then sort, then range), and check each query withexplain("executionStats"): it should use an index scan (IXSCAN) and examine about as many documents as it returns. MongoDB creates only the_idindex for you. Every index slows down writes, so drop the ones that$indexStatsshows unused. On Atlas, the Performance Advisor suggests indexes for slow queries. (MongoDB, Development Checklist: schema design, The ESR Guideline, Interpret Explain Plan Results, Remove Unnecessary Indexes, Atlas Performance Advisor) - 5
MONGO-6If you shard a collection, choose a shard key with high cardinality, evenly spread and non-monotonic values, that most queries include, so that they go to one shard. You can reshard later, but a key that concentrates writes or forces broadcast queries limits scaling. (MongoDB, Choose a Shard Key, Development Checklist: sharding)
Consistency and transactions¶
- 8
MONGO-7Write data you can't lose withw: "majority", the default, on replica sets with at least three data-bearing voting members, and read from the primary with"majority"read concern where a client must read its own writes. Writes acknowledged withw: 1can be rolled back when the primary fails over. With an arbiter instead of a third data-bearing member, the implicit default can drop tow: 1. Don't use secondary reads to scale read throughput. (MongoDB, Rollbacks: avoid replica set rollbacks, Write Concern: implicit default, Read and write concern recommendations, Development Checklist: data durability, Development Checklist: replication) - 7
MONGO-8Use multi-document transactions only where several documents must change atomically, run them with the driver's callback API, which retries transient errors, and keep each one well under the 60-second default limit. Transactions cost more than single-document writes and don't replace good schema design; for many cases embedding is the better model. (MongoDB, Transactions, Best Practices: atomicity, Production Considerations: runtime limit) - 7
MONGO-9Leave retryable writes on, the driver default, and handle what they don't cover: retry failed operations with exponential backoff where that is safe (OPS-3), and make multi-document updates and deletes idempotent. Drivers retry inserts and single-document updates and deletes once after a network error or election;updateMany,deleteManyand individual writes inside a transaction aren't retried. (MongoDB, Retryable Writes, Development Checklist: drivers)
Connections¶
- 7
MONGO-10Create oneMongoClientper process when it starts, outside request and serverless handlers, and reuse it for every operation; sizemaxPoolSizefrom the number of concurrent requests, starting at 110–115% of the typical number. Each client has its own connection pool, so a client per request or per function invocation opens new connections every time and can exceed the database's connection limits. (MongoDB, Connection Pool Overview, Atlas, Manage Connections with AWS Lambda, Development Checklist: drivers)
Security¶
- 9
MONGO-11Self-managed: bind MongoDB to private interfaces, firewall its port so that only application hosts can reach it, and turn on access control, which is off by default. Atlas: never add0.0.0.0/0to the IP access list, and connect staging and production projects through private endpoints. This is how MongoDB appliesSEC-20. (MongoDB, Production Notes: use trusted networking environments, Network and Configuration Hardening: IP binding, Security Checklist: limit network exposure, Atlas, Configure IP Access List Entries, Atlas Architecture Center, network security recommendations) - 9
MONGO-12Never pass request data into a query filter or update document as an object: check that each value is a scalar of the expected type, or wrap it in$eq, so that a client can't send query operators such as{"$ne": null}. In Mongoose, turn on thesanitizeFilteroption. This appliesSEC-10. (CodeQL, Database query built from user-controlled sources, Mongoose, sanitizeFilter(), PortSwigger, NoSQL injection) - 8
MONGO-13Give each application its own database user with roles scoped to the databases and actions it needs, never a cluster-wide or administrator role, and require TLS on every connection (SEC-5,SEC-13). On Atlas, authenticate production workloads with Workload Identity Federation, AWS IAM or X.509 certificates; Atlas recommends password (SCRAM) users only for development and test. (MongoDB, Security Checklist: configure role-based access control, Security Checklist: encrypt communication, Atlas Architecture Center, authorization, Atlas Architecture Center, database authentication) - 7
MONGO-14Never build$where,$functionor$accumulatorexpressions from user input, and turn server-side JavaScript off when the application doesn't use it:--noscriptingorsecurity.javascriptEnabled: falseon self-managed servers, and the Allow Server-Side JavaScript setting on Atlas. These operators run arbitrary JavaScript on the server. (MongoDB, FAQ: how does MongoDB address query injection, Security Checklist: secure configuration options, Server-side JavaScript: disable, Atlas, Allow Server-Side JavaScript)
Backups and upgrades¶
- 8
MONGO-15Back up production clusters with point-in-time recovery, keep a copy in a second region, and test restores regularly (DATA-8). On Atlas, turn on Cloud Backup with Continuous Cloud Backup, multi-region snapshot distribution and a Backup Compliance Policy. Atlas Free clusters have no Atlas backups. Self-managed deployments need Ops Manager or Cloud Manager, or file system snapshots with journaling;mongodumpsuits only small deployments. (Atlas Architecture Center, backup recommendations, Atlas Architecture Center, disaster recovery, Atlas, Back Up, Restore, and Archive Data, MongoDB, Operations Checklist: backups, Backup Methods for a Self-Managed Deployment) - 7
MONGO-16Choose the upgrade path on purpose. On Atlas clusters that upgrade automatically, declare the Stable API version in a strict client; elsewhere, test each new major version on a staging deployment first, upgrade before the current one reaches end of life, and raise the feature compatibility version only after testing, because after that you can't downgrade. A strict Stable API client rejects commands outside the API, so that server upgrades don't change the application's behavior. This appliesSEC-17. (MongoDB, Stable API: create a strict client, MongoDB Versions and Upgrade Paths: before you upgrade, feature compatibility version, MongoDB Software Lifecycle Schedules)
How to enforce¶
Tools that check the key rules above automatically, in CI, the IDE or a commit hook. "Partly" means the tool covers only some of what the rule asks.
- 7 Atlas Resource Policies: organization-wide policies, written in Cedar, that Atlas checks on every change from the UI, API, CLI or Terraform. They can forbid
/0entries in IP access lists, require an empty list so that only private endpoints connect, and impose a minimum TLS version. Partly checksMONGO-11,MONGO-13andSEC-20. - 6 CodeQL, Database query built from user-controlled sources and NoSQL Injection (Python): code-scanning queries that trace request data into MongoDB queries in JavaScript, TypeScript and Python. Partly checks
MONGO-12. - 6
notablescanserver parameter: set it on themongodthat integration tests run against, so that every query that needs a collection scan fails. Don't set it in production. Partly checksMONGO-5. - 4 Semgrep
mongodb-nosqlirule: flags non-constant data passed to$wherethrough the Java driver. Partly checksMONGO-14.
Tutorials and further reading¶
- 6 Designing Your Schema (MongoDB docs): the step-by-step schema design process: identify the workload, map relationships and apply design patterns.