Introducing Dragonfly Cloud! Learn More

Question: How do you remove a shard from MongoDB?

Answer

Removing a shard from a MongoDB cluster involves several steps to ensure data integrity and cluster stability. The process redistributes the data from the shard you want to remove to the remaining shards in the cluster before the actual removal. Here are the general steps to remove a shard:

Step 1: Drain the Shard

First, you need to start draining the shard, which means moving all chunks of data from the shard you want to remove to other shards. Use the sh.removeShard() command for this purpose.

db.adminCommand({removeShard: "<shardName>"})

Replace <shardName> with the name of the shard you wish to remove. Initially, this command will return a state indicating that the shard removal process has started but not yet completed.

Step 2: Monitor the Draining Process

Continuously check the status of the shard removal by running the sh.removeShard() command again. It may take some time depending on the amount of data that needs to be moved.

db.adminCommand({removeShard: "<shardName>"})

When the process is complete, the command will return a message indicating that the shard can now be safely removed.

Step 3: Remove the Shard

After all data has been drained from the shard, and the sh.removeShard() command indicates it's safe to remove, you physically remove the shard from your cluster. This step might involve decommissioning the hardware or repurposing it for other tasks if the shard was hosted on dedicated servers.

Additional Considerations

  • Backup: Always ensure you have a recent backup of your data before starting the removal process.
  • Monitoring: Keep an eye on your cluster’s performance and health throughout the process using MongoDB monitoring tools.
  • Configuration Servers: Update any manual configurations that reference the removed shard.

By following these steps carefully, you can remove a shard from your MongoDB cluster without losing data or significantly impacting your cluster's performance.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today 

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