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:
- Connect to the mongo shell on the node to be removed.
- 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?
Other Common MongoDB Performance Questions (and Answers)
- How to check MongoDB replication status?
- How do you connect to a MongoDB cluster?
- How do you clear the cache in MongoDB?
- How many connections can MongoDB handle?
- How to check MongoDB cluster status?
- How to change a MongoDB cluster password?
- How to restart a MongoDB cluster?
- How do I reset my MongoDB cluster password?
- How does the $in operator affect performance in MongoDB?
- Is MongoDB aggregate slow?
- How can you set up a MongoDB local replica set?
- How to delete a MongoDB cluster?
Free System Design on AWS E-Book
Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.
Switch & save up to 80%
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost