Navigation
This version of the documentation is archived and no longer supported.

Shard Key Indexes

All sharded collections must have an index that starts with the shard key. If you shard a collection without any documents and without such an index, the shardCollection command will create the index on the shard key. If the collection already has documents, you must create the index before using shardCollection.

This shard key index can be an index of the shard key itself, or a compound index where the shard key is a prefix of the index.

Important

The index on the shard key cannot be a multikey index.

A sharded collection named people has for its shard key the field zipcode. It currently has the index { zipcode: 1 }. You can replace this index with a compound index { zipcode: 1, username: 1 }, as follows:

  1. Create an index on { zipcode: 1, username: 1 }:

    db.people.createIndex( { zipcode: 1, username: 1 } );
    
  2. When MongoDB finishes building the index, you can safely drop the existing index on { zipcode: 1 }:

    db.people.dropIndex( { zipcode: 1 } );
    

Since the index on the shard key cannot be a multikey index, the index { zipcode: 1, username: 1 } can only replace the index { zipcode: 1 } if there are no array values for the username field.

If you drop the last valid index for the shard key, recover by recreating an index on just the shard key.

For restrictions on shard key indexes, see Shard Key Limitations.