MongoDB Shard Keys
What Is Shard Keys?
A shard key is one or more fields that MongoDB uses to distribute a collection's documents across shards. The key determines where each document lives and how well reads and writes spread. A good shard key has high cardinality (many distinct values), low frequency (no single value dominates), and does not increase monotonically, which would send all new writes to one shard.
Why It Matters
| Reason | Benefit |
|---|---|
| Even data distribution | A good key spreads documents so no shard is overloaded. |
| Fast targeted queries | Queries containing the key hit few shards. |
| Scalable writes | Hashed or compound keys distribute inserts across shards. |
| Avoid expensive mistakes | Poor keys cause hot shards, and changing them later is costly. |
How To Use It
- List your most frequent queries and writes, and the fields they filter on.
- Pick candidate fields that appear in most queries and have many distinct values.
- Reject candidates that increase monotonically, like timestamps or counters, unless hashed.
- Decide between ranged sharding for range queries and hashed sharding for even writes.
- Create an index that supports the key on the collection if it has data.
- Enable sharding on the database if needed and run sh.shardCollection().
- Monitor distribution with sh.status() and db.collection.getShardDistribution().
mongosh Examples
// Connect to mongos
sh.enableSharding("shop")
// Hashed key: even distribution of writes
db.getSiblingDB("shop").events.createIndex({ userId: "hashed" })
sh.shardCollection("shop.events", { userId: "hashed" })
// Compound ranged key: targets queries by customer, spreads by date
db.getSiblingDB("shop").orders.createIndex({ customerId: 1, orderDate: 1 })
sh.shardCollection("shop.orders", { customerId: 1, orderDate: 1 })
// Check how data is spread
sh.status()
db.getSiblingDB("shop").orders.getShardDistribution()
// Targeted: includes the shard key prefix
db.getSiblingDB("shop").orders.find({ customerId: 42 }) Edge Cases & Pitfalls
Hot shards from monotonic keys
A key such as a timestamp or ObjectId sends all new inserts to the shard owning the highest range. Hash it or combine it.
Low cardinality
A key like country with a few values limits how many chunks can exist, so data cannot spread evenly.
Jumbo chunks
If one key value has too many documents, its chunk cannot be split or moved. Pick a key with better distribution.
Scatter-gather queries
Queries that omit the shard key must query every shard, which hurts performance at scale.
Hard to change
Resharding is possible in newer versions but operationally heavy. Plan the key before you shard.
Cheat Sheet
| Topic | Detail |
|---|---|
| Cardinality | Number of distinct key values; higher allows more chunks and better splitting |
| Frequency | How often a value appears; a very common value creates a jumbo chunk |
| Monotonic change | Keys that always increase send inserts to one shard (hot shard) |
| Ranged sharding | Keeps nearby key values together; good for range queries |
| Hashed sharding | Hashes the key for even distribution; poor for range queries |
| Compound shard key | Combine fields, e.g. { customerId: 1, orderDate: 1 }, to improve selectivity |
| sh.shardCollection() | Shard a collection with a key |
| Targeted query | Query includes the shard key, so mongos routes to specific shards |
| Scatter-gather | Query without the shard key is sent to all shards |
| reshardCollection | Command to change a collection's shard key in newer versions |
Key Takeaways
Choose the shard key to match your most common queries so they hit one or a few shards. Avoid keys like timestamps or auto-increment ids on their own; use a hashed key or a compound key instead.
Frequently Asked Questions
What is a shard key?
A field or combination of fields that determines how a collection's documents are distributed across shards.
What makes a good shard key?
High cardinality, even value frequency, no monotonic growth, and presence in the common queries so they can be targeted.
Hashed or ranged sharding?
Hashed gives even write distribution but not efficient range queries. Ranged keeps related values together and supports range queries, but can create hotspots.
Can I change a shard key later?
Recent MongoDB versions support resharding a collection, and you can refine a key by adding suffix fields, but it is better to choose carefully upfront.
What is a hot shard?
A shard receiving a disproportionate share of reads or writes, often caused by a monotonically increasing shard key.
Do I need an index for the shard key?
Yes. A collection with data needs an index that starts with the shard key before sharding. MongoDB creates it for an empty collection.
Next: MongoDB mongos Router
Continue the MongoDB learning path.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
8 people found this page helpful
