OPTIONS
翻译或纠错本页面

分片集合

定义

shardCollection

开启一个集合的分片,之后MongoDB就可以在分片间分配这个集合的数据.在运行 shardCollection 命令之前必须先在集合所在的数据库上运行 enableSharding 命令, shardCollection 使用以下格式:

{ shardCollection: "<database>.<collection>", key: <shardkey> }

命令 shardCollection 有以下字段:

Field Type Description
shardCollection 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 index must exist prior to the shardCollection command, unless the collection is empty. If the collection is empty, in which case MongoDB creates the index prior to sharding the collection. New in version 2.4: The key may be in the form { field : "hashed" }, which will use the specified field as a hashed shard key.
unique Boolean When true, the unique option ensures that the underlying index enforces a unique constraint. Hashed shard keys do not support unique constraints.
numInitialChunks integer Specifies the number of chunks to create initially when sharding an empty collection with a hashed shard key. MongoDB will then create and balance chunks across the cluster. The numInitialChunks must be less than 8192 per shard. If the collection is not empty, numInitialChunks has no effect.

注意事项

使用

Do not run more than one shardCollection command on the same collection at the same time.

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

片键

如何选择一个好的片键,以使得集群中的分片负载均衡较好,需要一些规划.参见 片键 来选择一个好的片键.

哈希片键

2.4 新版功能.

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

注解

如果在创建哈希片键时,数据块正在迁移,那么在自动均衡过程使得到集合均衡之前,初始化的数据块可能不均衡.

示例

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

db.runCommand( { shardCollection: "records.people", key: { zipcode: 1 } } )