MongoDB Replication is Easy

August 8, 2010 - 2 minute read -
database functional programming mongodb

Database replication with MongoDB is easy to setup. Replication duplicates all of the data from a master to one or more slave instances and allows for safety and quick recovery in case of a problem with your master database. Here is an example of how quick and easy it is to test out replication in MongoDB. Create a couple of directories for holding your mongo databases.

mkdir master slave
Start by running an instance of the "master" database.
cd master
mongod  --master --dbpath .
Start a new terminal window and continue by running an instance of a "slave" database. This example is running on the same machine as master which is great for testing, but wouldn't be a good setup if you were really trying to implement replication in a production environment since you would still have a single-point-of-failure in the single server case.
cd slave
mongod --slave --port 27018 --dbpath . --source localhost
And start another terminal window to use as the client
mongo {name:'Geoff Lane'} ) {name:'Joe Smith'} )
db.person.find() {name:'Jim Johnson', age: 65} )
Now kill the master instance in your terminal with Control+C. This simulates the the master server dying. Lastly connect to the slave instance with a mongo client by specifying the port.
mongo --port 27018
As you can see, the db.person.find() returns all of the values that were saved in the master list as well which shows that replication is working. One of the other interesting facts is that you can start a slave instance even after the mongod master is already running and has data and all of the data will be replicated over to the slave instance as well. This all works without ever shutting down your mongod master instance. This allows you to add replication after the fact with no downtime. For more on MongoDB check out these books: * MongoDB: The Definitive Guide * The Definitive Guide to MongoDB: The NoSQL Database for Cloud and Desktop Computing * MongoDB for Web Development (Developer's Library)