Dragonfly Cloud is now available in the AWS Marketplace - learn more

Question: How do you convert a MongoDB standalone server into a replica set?

Answer

Converting a MongoDB standalone server into a replica set involves several steps, allowing the server to support high availability and data redundancy. Here's a comprehensive guide:

Step 1: Shutdown the Standalone Server

First, cleanly shut down your MongoDB standalone server. You can do this by connecting to the MongoDB shell and issuing the shutdown command:

use admin db.shutdownServer()

Step 2: Restart with Replica Set Option

Restart the MongoDB instance with the --replSet option. This option specifies the name of the replica set. Replace <replSetName> with your desired replica set name.

mongod --port 27017 --dbpath /data/db --replSet <replSetName>

Remember to adjust the port and dbpath as per your configuration.

Step 3: Initialize the Replica Set

After restarting the MongoDB instance with the --replSet option, connect to the MongoDB shell and initialize the replica set:

rs.initiate()

This command will initiate the replica set with a single member (the current standalone server).

Step 4: Verify Replica Set Configuration

You can verify the replica set configuration and status by running:

rs.status()

Additional Steps for Adding More Members

If you plan to add more members to your newly created replica set, you can do so using the rs.add() command. For example, to add a new member with the hostname mongodb2.example.net:

rs.add("mongodb2.example.net:27017")

Ensure that each member you wish to add is already running MongoDB with the --replSet option configured with the same replica set name.

Conclusions

Converting a MongoDB standalone server into a replica set enables features like automatic failover and data redundancy, which are critical for production environments where data availability and reliability are paramount. Following the steps above, you can transition smoothly from a standalone setup to a robust replica set configuration.

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

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