Docs HomeMongoDB Manual

sh.enableSharding()

Definition定义

sh.enableSharding(database, primaryShard)
Note

Changed in version 6.0.6.0版更改。

Starting in MongoDB 6.0, this method is not required to shard a collection.从MongoDB 6.0开始,不需要此方法来分片集合。

Explicitly creates a database. 显式创建数据库。Use the mongosh method sh.shardCollection() to shard collections on the database. 使用mongosh方法sh.shardCollection()对数据库上的集合进行分片。The mongosh method sh.enableSharding() wraps the enableSharding command.mongosh方法sh.enableSharding()封装enableSharding命令。

Important

mongosh Method

This page documents a mongosh method. This is not the documentation for database commands or language-specific drivers, such as Node.js.

For the database command, see the enableSharding command.

For MongoDB API drivers, refer to the language-specific MongoDB driver documentation.

For the legacy mongo shell documentation, refer to the documentation for the corresponding MongoDB Server release:

mongo shell v4.4

Syntax语法

The sh.enableSharding() has the following form:sh.enableSharding()具有以下形式:

sh.enableSharding(
<database>,
<primary shard> // Optional. Available starting in MongoDB 4.2.2 (and 4.0.14)
)

Parameter参数

The sh.enableSharding() method takes the following parameter:sh.enableSharding()方法采用以下参数:

Parameter参数Type类型Description描述
databaseStringThe name of the database you want to create.要创建的数据库的名称。
primaryShardStringOptional.可选的。The primary shard for the database; the primary shard contains the unsharded collection for this database. 数据库的主分片;主分片包含该数据库的未排序集合。In general, rather than explicitly specifying the primary shard, it is recommended to let the balancer select the primary shard instead.通常,建议平衡器选择主分片,而不是显式指定主分片。
Warning

Tip

In general, you should not need to specify the primary shard. 通常,您不需要指定主分片。Allow the balancer to select the primary shard instead. 允许平衡器选择主分片。
Available starting in MongoDB 4.2.2 (and 4.0.14)从MongoDB 4.2.2(和4.0.14)开始提供

Behavior行为

Write Concern撰写关注事项

mongos uses "majority" for the enableSharding command and its helper sh.enableSharding().mongos使用"majority"作为enableSharding命令及其助手sh.enableSharding()

Primary Shard初级分片

In general, you should not need to specify the primaryShard in the command. Instead, allow the balancer to select the primary shard.通常,您不需要在命令中指定primaryShard。相反,允许平衡器选择主分片。

However, if you do specify the primary shard for a database and the database is already enabled for sharding with a different primary shard, the operation returns an error and the primary shard for the database remains as before. 但是,如果您确实为数据库指定了主分片,并且该数据库已经启用了与其他主分片的分片,则该操作将返回一个错误,并且数据库的主分片与以前一样。To change the primary shard for a database, use the movePrimary command instead.要更改数据库的主分片,请改用movePrimary命令。

Example实例

The following example, run from a mongos, explicitly creates the shardTest database:以下示例从mongos运行,显式创建shardTest数据库:

sh.enableSharding("shardTest")

To verify, run sh.status().要进行验证,请运行sh.status()