Navigation

enableSharding

Definition

enableSharding

The enableSharding command enables sharding on the specified database. Once you enabled sharding for a database, you can use the shardCollection command to shard collections in that database.

The mongo shell method sh.enableSharding() wraps the enableSharding command.

Syntax

The enableSharding command has the following syntax:

  • Recommended. Specify just the database for which to enable sharding.

    db.adminCommand( {
       enableSharding: "<database name>"
    } )
    
  • Optionally, starting in MongoDB 4.2.2 (and 4.0.14), you can include the primary shard specification in the command, although this is not recommended:

    db.adminCommand( {
       enableSharding: "<database name>",
       primaryShard: "<shard name>"  // Available starting in MongoDB 4.2.2 (and 4.0.14)
    } )
    

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

Fields

The command takes the following fields:

Field Type Description
enableSharding String

The database for which you wish to enable sharding.

primaryShard String

Optional. 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.

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)

Returns

The command returns a document that contains status of the operation.

Behavior

Write Concern

mongos uses "majority" for the enableSharding command and its helper 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.

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.

Example

The following command, run from a mongos, enables sharding for the test database:

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

To verify, run sh.status().