Question: How do you remove a node from a MongoDB cluster?

Answer

Removing a node from a MongoDB cluster, specifically from a replica set, is an operation that should be performed with care to ensure the cluster continues to operate smoothly. Here's how you can safely remove a node from a MongoDB replica set:

Step 1: Ensure Replica Set Stability

Before removing any node, ensure that:

  • Your replica set has enough members to maintain a majority after the node is removed. A majority is required for the replica set to elect a primary.
  • The node to be removed is not the current primary. If it is, initiate a manual failover by stepping down the primary using rs.stepDown().

Step 2: Remove the Node from the Replica Set Configuration

Connect to the mongo shell of one of the remaining nodes in the replica set and issue the following commands:

cfg = rs.conf() cfg.members = cfg.members.filter(member => member.host !== 'nodeToRemove:port') rs.reconfig(cfg)

Replace 'nodeToRemove:port' with the actual hostname and port of the node you want to remove.

Step 3: Shutdown the Removed Node

After successfully removing the node from the replica set configuration, you can shut down the removed node:

  1. Connect to the mongo shell on the node to be removed.
  2. Use the following command to shut down the MongoDB server:
db.shutdownServer()

Step 4: Post-Removal Steps

  • Monitor the replica set to ensure it remains stable and there are no unexpected issues.
  • Update any application or infrastructure configurations that referenced the removed node.

Important Consideration

If the removed node was holding a significant amount of data, consider balancing the data across the remaining nodes in the replica set. This may happen automatically depending on your cluster's settings, but it's good practice to monitor disk space and load distribution post-removal.

This process is for replica sets. For sharded clusters, removing a shard involves additional steps and considerations, as data must be migrated away from the shard before removal.

Was this content helpful?

Start building today

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