Question: What are some important MongoDB sharding commands?


Sharding in MongoDB is a method for distributing data across multiple servers. It is used to scale horizontally by splitting data into ranges and distributing them across shards. Here are some essential commands related to sharding in MongoDB:

1. Enable Sharding for a Database

To enable sharding on a database, use the sh.enableSharding() method:


Replace "databaseName" with the name of your database.

2. Shard a Collection

After enabling sharding on a database, you need to shard the collections within that database. Use the sh.shardCollection() method:

sh.shardCollection("databaseName.collectionName", { key: 1 })

In this command, replace "databaseName.collectionName" with the namespace of your collection and { key: 1 } with the shard key pattern.

3. Check Sharding Status

To check the status of sharding for your cluster, you can use:


This command provides an overview of your sharded cluster, including databases, collections, and their shard keys.

4. Add a Shard

To add a new shard to the cluster, use the sh.addShard() command:


Replace "shardConnectionString" with the connection string of the mongod instance you want to add as a shard.

5. Remove a Shard

Removing a shard from the cluster involves several steps, starting with draining the shard. Begin with:

db.runCommand({ removeShard: "shardName" })

Replace "shardName" with the name of the shard you wish to remove. This command will start the removal process, which involves migrating chunks from the shard being removed to other shards.

6. Balancing Shards

MongoDB automatically balances chunks across shards. However, if you need to manually start or stop the balancer, use:

// Start balancer sh.startBalancer() // Stop balancer sh.stopBalancer()


These commands are fundamental when managing a sharded MongoDB cluster. They allow you to enable sharding, shard collections, monitor sharding status, and manage shards within your cluster. Proper understanding and usage of these commands are crucial for maintaining a well-performing and balanced distributed database system.

Was this content helpful?

Start building today

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.