Docs Menu

Docs HomeDevelop ApplicationsMongoDB Manual

Shard a Collection

On this page

  • Shard Key Fields and Values
  • Missing Shard Key Fields
  • Change a Document's Shard Key Value
  • Change a Collection's Shard Key

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

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().

Documents in sharded collections can be missing the shard key fields. A missing shard key falls into the same range as a null-valued shard key. See Missing Shard Key Fields.

In version 4.2 and earlier, shard key fields must exist in every document to be able to shard a sharded collection. To set missing shard key fields, see Set Missing Shard Key Fields.

Starting in MongoDB 4.2, you can update a document's shard key value unless the shard key field is the immutable _id field. In MongoDB 4.2 and earlier, a document's shard key field value is immutable.

For details on updating the shard key value, see Change a Document's Shard Key Value.

Starting in MongoDB 5.0, you can reshard a collection by changing a document's shard key.

You can refine a shard key by adding a suffix field or fields to the existing shard key.

In MongoDB 4.2 and earlier, the choice of shard key cannot be changed after sharding.

←  Shard KeysChoose a Shard Key →