DynamoDB vs MongoDB: Access-Pattern Keys or Indexed Documents
DynamoDB makes access paths explicit in keys and indexes; MongoDB permits richer document queries, but at scale the shard key still decides which queries remain local.
Situation
A domain object often looks natural as a MongoDB document and unnatural as a collection of DynamoDB items. That observation is useful but incomplete. Production systems do not store objects in isolation: they enforce conditional updates, retrieve alternate views, distribute hot tenants, migrate schemas, and recover indexes after failure.
DynamoDB and MongoDB can both represent an order aggregate, but they move complexity to different places. DynamoDB encourages the team to enumerate access patterns and encode them into partition and sort keys, with global secondary indexes for alternate keys. MongoDB stores nested BSON documents and offers compound, multikey, partial, text, geospatial, and other indexes. Once a MongoDB collection is sharded, however, the shard key becomes an equally consequential access-path decision.
The Problem
Assume an order service needs these operations: fetch an order by ID, list a customer’s recent orders, find open orders by fulfillment region, update an order conditionally, and retain an immutable status history. The workload also has a small number of very large customers.
The decision is not “known versus unknown queries.” Every production database needs bounded access paths. The question is: should the system pay for predeclared key-oriented views, or pay for document indexes and a sharding layer that can support the expected query evolution?
Two Ways to Materialize Access
flowchart TD
A["Order mutation"] --> B{"Data model"}
B -->|DynamoDB| C["Base item collection"]
C --> D["Global secondary indexes"]
B -->|MongoDB| E["BSON document"]
E --> F["Compound and specialized indexes"]
D --> G["Measure capacity, lag, and hot keys"]
F --> H["Measure plans, cache, and shard targeting"]
G --> I["Validate correctness and recovery"]
H --> I
DynamoDB: Access Patterns Become Physical Representations
A DynamoDB composite primary key groups items by partition key and orders them by sort key. One design could store order metadata and status events in an ORDER#id item collection, while a GSI keyed by customer supports recent-order lookup. Another sparse GSI could include only open orders by region.
This is not a requirement to put an entire application into one table. Single-table design can co-locate related entities, but table boundaries should follow operational isolation, lifecycle, security, and change ownership as well as query efficiency.
Each GSI is an eventually consistent replicated structure. Its projected attributes determine additional write and storage cost. In provisioned mode, insufficient GSI write capacity can throttle writes to the base table. A low-cardinality status or region key can also become hot unless it is combined with sufficient distribution and the reader can merge shards.
DynamoDB transactions can group multiple item operations, and condition expressions support optimistic concurrency. Those capabilities have documented size and operation limits and consume additional capacity. The schema should keep the common correctness boundary small rather than treating transactions as a substitute for locality.
MongoDB: Flexible Predicates Become Index and Routing Work
MongoDB documents can preserve an aggregate that is read and updated together. Compound indexes support repeated predicates and sort orders; field order matters, and MongoDB’s ESR guideline places equality fields before sort and range fields in the common case. An index-prefix mismatch can force more keys or documents to be examined.
There is no responsible rule such as “more than six indexes is bad” or “indexes must stay below half the cache.” The boundary depends on document size, update rate, key width, selectivity, compression, working set, and storage latency. Measure index usage, cache pressure, query plans, and write latency. Remove redundant indexes only after workload evidence and rollback planning.
In a sharded cluster, the shard key determines placement. Queries containing the shard key or a usable prefix can target shards; other queries can scatter. Hashed sharding distributes monotonically changing values more evenly but sacrifices range locality. Ranged sharding preserves locality but can concentrate writes if the leading field is monotonic or skewed.
MongoDB supports multi-document transactions, including across shards, but the documentation states that cross-shard transactions cost more than single-shard transactions. Read concern snapshot provides a consistent view of majority-committed data at one point in time across shards when used with the documented transaction and majority-write conditions. Frequent distributed transactions are a signal to revisit the aggregate and shard key.
Change Is Possible, Not Free
DynamoDB access-pattern change commonly adds a GSI, a new item representation, or a stream-driven projection. The transition needs dual-read or versioned-read behavior until backfill and propagation are complete. Deleting an old path requires evidence that no caller uses it.
MongoDB can refine a shard key or reshard a collection. Since MongoDB 5.0, resharding can change the shard key; MongoDB 8.0 also supports redistributing on the same key in specified cases. These features reduce migration risk but do not eliminate capacity, duration, oplog, storage, or operational planning. Version-specific prerequisites must be checked against the deployed edition.
In Practice
The documented pattern is that both systems require query inventory and physical verification. AWS asks DynamoDB designers to calculate activity across table and index partition keys. MongoDB documents shard targeting and provides explain to show whether an operation uses an index and how much work it performs.
For the assumed order workload, the engineering action is to build both critical and awkward paths. In DynamoDB, measure consumed capacity and throttling reasons on the base table and each GSI, including the largest customer. In MongoDB, inspect winning plans, documents and keys examined, scatter behavior, cache metrics, and chunk distribution. Then simulate an access-pattern change in each candidate.
The result should show not merely which prototype is faster today, but which change procedure is understandable and reversible. The learning is that flexibility is a budget: DynamoDB spends it on explicit new representations; MongoDB spends it on indexes, routing, and potentially resharding.
Version and Safety Boundary
This article targets currently supported MongoDB releases, with MongoDB 8.0 behavior checked explicitly where mentioned. Do not copy legacy index-build advice such as relying on background: true; modern MongoDB changed index build behavior and the option is ignored in current releases. Validate procedures against the exact minor version and deployment type before production use.
Where It Breaks
| Choice | Failure mode | Required control |
|---|---|---|
| DynamoDB | New query has no key-oriented path | Versioned GSI or projection migration with reconciliation |
| DynamoDB | GSI key or base key is hot | Per-resource throttling reasons and key-frequency analysis |
| DynamoDB | Application assumes immediate GSI visibility | Stale-read and read-after-write contract |
| MongoDB | Query cannot target shards | explain review, shard-key redesign, or explicit scatter budget |
| MongoDB | Index set exceeds memory and write budget | Index usage, cache, latency, and storage evidence |
| MongoDB | Cross-shard transactions become the common path | Redesign aggregate or shard key before scaling |
What to Do Next
- Problem: “Flexible” and “access-pattern-first” are labels, not capacity or correctness models.
- Solution: Map each query to its key, index, shard-routing, and transaction behavior.
- Proof: Test hot tenants, index propagation, query plans, cache pressure, distributed transactions, and schema change.
- Action: Approve the design only with a versioned access-pattern catalog and a rehearsed migration path for the next likely query.