Docs Menu
Docs Home
/
Database Manual
/

Shard Keys

The shard key is either a single indexed field or multiple fields covered by a compound index that determines the distribution of the collection's documents among the cluster's shards. For details, see Shard Key Indexes.

MongoDB divides the span of shard key values (or hashed shard key values) into non-overlapping ranges of shard key values (or hashed shard key values). Each range is associated with a chunk, and MongoDB attempts to distribute chunks evenly among the shards in the cluster.

Diagram of the shard key value space segmented into smaller ranges or chunks.

You can use the mongosh method sh.shardCollection() to shard a collection. To shard a collection, you must specify the full namespace of the collection that you want to shard and the shard key.

sh.shardCollection(<namespace>, <key>) // Optional parameters omitted

namespace

Specify the full namespace of the collection that you want to shard ("<database>.<collection>").

key

Specify a document { <shard key field1>: <1|"hashed">, ... } where

For more information on the sharding method, see sh.shardCollection().

The choice of shard key affects the creation and distribution of data across the available shards. The distribution of data affects the efficiency and performance of operations within the sharded cluster. The ideal shard key allows MongoDB to distribute documents evenly throughout the cluster while also facilitating common query patterns.

For details, see the Choose a Shard Key page.

MongoDB provides two ways to change a shard key. How to change a shard key:

For details, see the Change a Shard Key page.

You can change the value for the shard key field in any document in your collection unless the shard key field is the _id field. This can affect which shard the document lives on.

For details, see Change a Document's Shard Key Value.

It is possible for documents in your collection to be missing fields that your shard key specifies. By default, documents that that are missing fields specified by your shard key live in the the same chunk range as shard keys with null values.

For details, see Set Missing Shard Key Fields.

You can use the db.printShardingStatus() method to display the shard key used for your collection.

For details, see Display a Shard Key.

Some common shard key issues caused by a suboptimal shard key are:

  • Jumbo chunks

  • Uneven load distribution

  • Decreased query performance

For details, see Troubleshoot Shard Keys.

Back

Router (mongos)

Earn a Skill Badge

Master "Sharding Strategies" for free!

Learn more

On this page