{"success":true,"name":"choose-a-mongodb-shard-key-like-it-s-permanent-because-it-ne","description":"Sharding a MongoDB collection or designing for future sharding","category":"ai-brimind","path":"ai-brimind/choose-a-mongodb-shard-key-like-it-s-permanent-because-it-ne/SKILL.md","file":"SKILL.md","content":"---\nname: choose-a-mongodb-shard-key-like-it-s-permanent-because-it-ne\ndescription: \"Sharding a MongoDB collection or designing for future sharding\"\n---\n\n# Choose a MongoDB Shard Key Like It's Permanent — Because It Nearly Is\n\n## When to use\nProject uses MongoDB at scale, and a collection is being sharded or the team is designing schemas expected to shard later.\n\n## Example request\nSharding on a timestamp → all new writes hit one shard (monotonic key = hotspot); hashed _id or a compound key spreads them. Queries never including the shard key → every query broadcasts to all shards (scatter-gather); the key must appear in the main query patterns. Picking a low-cardinality field like country → a handful of giant chunks that can't split; cardinality is a hard requirement. 'We'll fix the key later' → resharding exists but is heavy; the key deserves design-time seriousness. Each maps to 'the shard key is chosen against your write pattern AND your query pattern at once'.\n\n## Instructions\nAct as a distributed-systems designer who knows the shard key is the one MongoDB decision that punishes casualness for years. When sharding is real or realistically coming: (1) gather the two facts the key must serve before proposing anything — the write pattern (what arrives, how fast, is the natural key monotonically increasing like time or ObjectId?) and the dominant query patterns (which fields do the hot queries filter on?), (2) evaluate candidates against the three named criteria: cardinality (enough distinct values to split into many chunks), frequency (no single value dominating), and monotonicity (ever-increasing keys funnel all inserts to one shard — the classic hotspot), (3) match to strategy: hashed sharding spreads monotonic keys but sacrifices range queries; ranged compound keys (e.g. tenantId + timestamp) keep related data together AND spread load — often the honest answer, (4) verify the winner appears in the main query filters, because queries missing the shard key scatter-gather across every shard, (5) if current scale doesn't need sharding, still avoid designs that would make a good key impossible later, and say when sharding would become relevant. If write/query patterns are unmeasured, ask for numbers. Only commit once the key survives both patterns on paper, and explain what hotspot or scatter-gather the choice specifically prevents.\n\n## Metadata\n- role: developer\n- level: tactical\n- places: vibeCoding\n- origin: ai.brimind.pro skill #1158\n","linked_files":[],"origin":"ai.brimind.pro","owner_id":null,"source":"router"}