MongoDB Shard Keys

Intermediate
9 min read
Updated: Nov 2026
Getting Started

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

ReasonBenefit
Even data distributionA good key spreads documents so no shard is overloaded.
Fast targeted queriesQueries containing the key hit few shards.
Scalable writesHashed or compound keys distribute inserts across shards.
Avoid expensive mistakesPoor keys cause hot shards, and changing them later is costly.

How To Use It

  1. List your most frequent queries and writes, and the fields they filter on.
  2. Pick candidate fields that appear in most queries and have many distinct values.
  3. Reject candidates that increase monotonically, like timestamps or counters, unless hashed.
  4. Decide between ranged sharding for range queries and hashed sharding for even writes.
  5. Create an index that supports the key on the collection if it has data.
  6. Enable sharding on the database if needed and run sh.shardCollection().
  7. Monitor distribution with sh.status() and db.collection.getShardDistribution().

mongosh Examples

mongosh
// 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

TopicDetail
CardinalityNumber of distinct key values; higher allows more chunks and better splitting
FrequencyHow often a value appears; a very common value creates a jumbo chunk
Monotonic changeKeys that always increase send inserts to one shard (hot shard)
Ranged shardingKeeps nearby key values together; good for range queries
Hashed shardingHashes the key for even distribution; poor for range queries
Compound shard keyCombine fields, e.g. { customerId: 1, orderDate: 1 }, to improve selectivity
sh.shardCollection()Shard a collection with a key
Targeted queryQuery includes the shard key, so mongos routes to specific shards
Scatter-gatherQuery without the shard key is sent to all shards
reshardCollectionCommand 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.

MongoDB mongos Router →

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful