翻译或纠错本页面

sh.shardCollection()

On this page

定义

sh.shardCollection(namespace, key, unique)

使用 key 作为 shard key 对一个集合开启分片. sh.shardCollection() 接收以下参数:

Parameter Type Description
namespace string The namespace of the collection to shard in the form <database>.<collection>.
key document

The index specification document to use as the shard key. The shard key determines how MongoDB distributes the documents among the shards.

Unless the collection is empty, the index must exist prior to the shardCollection command. If the collection is empty, MongoDB creates the index prior to sharding the collection if the index that can support the shard key does not already exist.

See also Shard Key Indexes

unique boolean When true, the unique option ensures that the underlying index enforces a unique constraint. Hashed shard keys do not support unique constraints.

注意事项

在执行 shardCollection 之后,MongoDB没有提供取消集群分片的方法.另外,执行 shardCollection 之后,集合的片键与文档中的片键值也不能够被修改.

Shard Keys

Choosing the best shard key to effectively distribute load among your shards requires some planning. Review 片键 regarding choosing a shard key and restrictions.

Hashed Shard Keys

Hashed shard keys use a hashed index of a single field as the shard key.

Use the form {field: "hashed"} to specify a hashed shard key. Hashed shard keys may not be compound indexes.

注解

If chunk migrations are in progress while creating a hashed shard key collection, the initial chunk distribution may be uneven until the balancer automatically balances the collection.

Uniqueness

If specifying unique: true:

  • 以下的操作在 records 数据库中的 people 集合上使用 zipcode 作为片键对此集合开启了分片.

  • If the collection is not empty, you must create the index first before using sh.shardCollection().

Although you can have a unique compound index where the shard key is a prefix, if using unique parameter, the collection must have a unique index that is on the shard key.

See also Sharded Collection and Unique Indexes

Example

Given the people collection in the records database, the following command shards the collection by the zipcode field:

sh.shardCollection("records.people", { zipcode: 1} )