对于 AI 代理:可在 https://www.mongodb.com/zh-cn/docs/llms.txt 获取文档索引—通过在任何 URL 路径后添加 .md 可获取所有页面的 Markdown 版本。
Docs 菜单

enableSharding(数据库命令)

enableSharding

注意

在版本6.0中进行了更改。

从 MongoDB 6.0 开始, 无需 使用此命令即可对集合进行分片。

The enableSharding command explicitly creates a database.

提示

In mongosh, this command can also be run through the sh.enableSharding() helper method.

Helper methods are convenient for mongosh users, but they may not return the same level of information as database commands. In cases where the convenience is not needed or the additional return fields are required, use the database command.

此命令可用于以下环境中托管的部署:

  • MongoDB Atlas:用于云中 MongoDB 部署的完全托管服务

该命令具有以下语法:

  • 推荐。 指定要创建的数据库:

    db.adminCommand(
    {
    enableSharding: "<database name>"
    }
    )
  • (可选)您可以在命令中包含主分片规范,但不建议这样做:

    db.adminCommand(
    {
    enableSharding: "<database name>",
    primaryShard: "<shard name>"
    }
    )

You can only run the enableSharding command on the admin database from a mongos instance.

该命令接受以下字段:

字段
类型
说明

字符串

要使用的数据库。 如果数据库不存在,则会创建该数据库。

字符串

可选。数据库的主分片;主分片包含此数据库的未分片集合。一般来说,建议让负载均衡器选择主分片,而不是明确指定主分片。

警告

提示

通常,您不需要指定主分片。允许负载均衡器选择主分片。

该命令返回包含操作状态的文档。

mongos uses "majority" for the enableSharding command and its helper sh.enableSharding().

一般来说,不需要在命令中指定 primaryShard。相反,允许负载均衡器选择主分片。

However, if you do specify the primaryShard in the command for a database and the database is already sharding enabled 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 movePrimary instead.

mongos运行以下命令,创建shardTest数据库:

db.adminCommand( { enableSharding: "shardTest" } )