I choose between MongoDB and PostgreSQL or MySQL based on data relationships, transaction boundaries, and scaling needs rather than hype. If a domain relies heavily on foreign-key integrity, complex multi-table joins, or frequent cross-entity ACID transactions like financial ledgers, PostgreSQL is my clear default—and for a few flexible attributes, PostgreSQL JSONB usually beats operating a second database. MongoDB shines when data is naturally polymorphic and aggregate-oriented—like e-commerce catalogs with varying product specs, CMS blocks, or event payloads—where you read and write a whole aggregate by key in one I/O with single-document atomicity, and may eventually need built-in horizontal sharding.
Unlike relational normalization, MongoDB modeling starts from access patterns: data read and updated together—with a clear upper bound—belongs embedded in one document. One-to-one or bounded one-to-few data, like an order with its address and line items, embeds cleanly for single-I/O reads and native single-document atomicity. Unbounded one-to-many arrays like millions of comments, many-to-many graphs, or independently hot entities must be referenced, otherwise unbounded arrays cause severe document rewrite amplification, multikey index bloat, WiredTiger cache pressure, and eventually hit the 16 MB BSON limit. In practice, I often blend both via the Subset Pattern—embedding the latest ten items while paging history from a separate collection—or the Bucket Pattern for time series.
Since MongoDB compound indexes are B-Trees following the leftmost prefix rule, I order keys by the ESR rule: Equality first, Sort second, Range last. Equality fields narrow the index slice immediately, and putting sort keys before range predicates lets the engine stream results in natural index order, eliminating blocking in-memory sorts that can hit the 100 MB sort limit (32 MB in older versions) or spill to disk. If all projected fields sit in the index, you even get a covered query with zero document reads. ESR is still a trade-off—if a range predicate is ultra-selective, sorting a handful of documents in memory can beat a wider scan, so always verify with explain executionStats.
To debug slow MongoDB queries, take slow ops from logs or the profiler and run explain("executionStats")—not plain explain(), which omits real scan counts. I look for four red flags: COLLSCAN, blocking in-memory SORT from a bad ESR order, and bloated totalKeysExamined or totalDocsExamined relative to nReturned, ideally near 1:1 (zero docs for covered queries). Deep skip() pagination degrades linearly because even with an index, MongoDB must walk and discard every skipped entry first. Fix it with keyset cursor pagination anchored on a unique composite key like (createdAt, _id)—not timestamp alone—giving consistent O(log N) index seeks without missing same-millisecond rows.
Likely follow-up: "When would you run explain("allPlansExecution"), and why can MongoDB's query plan cache suddenly pick a suboptimal index after data skew shifts?"
MongoDB separates durability, read isolation, and routing into three orthogonal settings: Write Concern, Read Concern, and Read Preference. With w: 1, a primary acknowledges a write before replicating it, risking permanent rollback on failover; critical writes should use w: "majority" plus journaling so committed data survives failovers. On reads, local can still expose uncommitted data that later rolls back, whereas majority guarantees reading only majority-committed data, and linearizable adds quorum freshness checks against stale split-brain primaries at higher latency. For core transactional paths, I pair majority write and read concerns with primary read preference, offloading only lag-tolerant analytics to secondaries—or using causal consistency sessions when read-your-own-writes matters on secondaries.
Likely follow-up: "Why can a write acknowledged with w: "majority" still be missed if you read with Read Preference secondary and default local read concern?"
The first principle of MongoDB transactions is designing documents so over 90 percent of writes stay atomic within a single document, where atomicity is native and fast. Modern MongoDB supports multi-document and cross-shard ACID transactions via WiredTiger snapshot isolation and two-phase commit, but they hold snapshots in cache, increase write conflicts, and enforce a default 60-second limit. I use them only when embedding is impossible—like transfers between separate accounts—keeping transactions short, free of remote calls, and wrapped in withTransaction to retry TransientTransactionError. If an app constantly needs heavy cross-collection transactions, PostgreSQL is usually the better fit.
A MongoDB Replica Set achieves high availability through one primary, multiple secondaries, an idempotent oplog, and majority elections. The primary turns writes into idempotent oplog operations—such as converting an increment into an explicit set—so secondaries replay them safely; after roughly 10 seconds of missed heartbeats, a surviving majority elects the freshest eligible secondary. Always run an odd number of voting nodes like 3 or 5 to avoid ties, and choose three data nodes—PSS—over Primary-Secondary-Arbiter. In PSA, losing the lone secondary leaves only one data copy, stalling w: "majority" writes and pinning the commit point until WiredTiger cache pressure destabilizes the primary.
当单副本集的存储容量、内存 Working Set 或者写入吞吐扛不住时,就要上 MongoDB 分片集群做水平扩展。
整个架构分三块,职责很清晰:最前面是无状态的 mongos 路由器,客户端连的是它,不用自己感知分片规则;中间是 Config Server 副本集(CSRS),专门存全局路由表,记录哪段范围的 Chunk 落在哪个分片上;最底层是真正的 Shard 分片,每个分片自己本身必须是一个完整的三节点副本集,保证单分片高可用。
在分片集群里做查询设计,最怕的就是 Scatter-Gather 广播查询。如果你的查询条件里带了分片键,mongos 查一下本地路由缓存,一箭精准打到对应的那一个分片,集群加分片吞吐就能线性往上涨;但要是查询没带分片键,mongos 根本不知道数据在哪,只能把请求同时广播给所有分片,等所有分片都查完回来再做归并排序。分片越多,这种广播查询的 P99 尾延迟越难看,还会把每个分片的 CPU 都消耗一遍,完全背离了分片扩展的初衷。
English PitchEnglish · ~65s
A MongoDB sharded cluster has three core components: stateless mongos routers that cache routing maps and merge results; a 3-node Config Server Replica Set (CSRS) storing shard metadata and Chunk ranges; and Shards—each itself a full replica set like PSS for HA—balanced across machines by the background Balancer moving ~128 MB chunks. We strongly avoid scatter-gather queries because they kill horizontal read scaling. Queries filtering on the shard key route directly to one shard (or a small subset for ranges), scaling throughput linearly. Omitting the shard key forces mongos to broadcast to all shards, consume cluster-wide CPU, and wait for the slowest shard, degrading P99 tail latency as shard count grows.
Key terms:mongos router, Config Server Replica Set (CSRS), Shard replica set, Chunk / Balancer, targeted vs scatter-gather
Likely follow-up: "When should you avoid sharding MongoDB altogether, and why can't a sharded collection directly enforce a unique index on a non-shard-key field?"
A good MongoDB shard key balances three criteria: high cardinality, even write spread, and query isolation. Low-cardinality keys like status or country fail by packing too many documents into unsplittable Jumbo Chunks that block Balancer migration and fill one shard. Range-sharding monotonically increasing keys like _id or createdAt sends 100 percent of new writes to the tail chunk on a single hotspot shard, wasting extra shards. Pure hashed or random keys spread writes but break range locality into scatter-gather. In production, use a compound key like { tenantId: 1, _id: 1 }—keeping tenant reads targeted while letting large tenants split—or hashed sharding ({ userId: "hashed" }) when point lookups dominate.
Key terms:cardinality / Jumbo Chunk, monotonic write hotspot, compound shard key, hashed vs range sharding, query isolation
Likely follow-up: "What trade-off do you accept with { _id: 'hashed' } sharding, and how does Zone Sharding help satisfy GDPR data residency?"
追问2 个
为什么对 { _id: "hashed" } 做哈希分片能解决写热点,它有什么缺点?
哈希函数把单调递增的 ObjectId 均匀映射到各个分片,彻底消除尾分片写热点;缺点是丧失了按 _id 做范围扫描的局部性——任何 _id > X 或按时间范围的查询都必须广播全部分片。
什么是 MongoDB 的 Zone Sharding(区域分片),海外业务为什么常用它?
Zone Sharding 允许把特定分片键区间(如 region: "EU"、region: "US")绑定到部署在对应地理区域(法兰克福 / 弗吉尼亚)的分片节点上,既降低跨洲访问延迟,又能直接满足 GDPR 等数据驻留合规要求。
易踩坑
建分片集合时顺手用默认 { _id: 1 } 做 Range 分片,上线后大促写入全部砸向最后一台分片。
只看平均数据分布没考虑“超级大租户/大 V 热点”,单独用 { tenantId: 1 } 导致大租户形成无法拆分的 Jumbo Chunk。