News Geek on the Block

Deploy MongoDB – Replication – Sharding

This page describe how to deploy MongoDB with Replication and Sharding.

Replication (Replica Set)

  1. Create the necessary data directories for each member by issuing a command similar to the following:

      mkdir -p /srv/mongodb/rs0-0 /srv/mongodb/rs0-1 /srv/mongodb/rs0-2
  2. Start your mongod instances in their own shell windows by issuing the following commands:

    First member:

      mongod --port 27017 --dbpath /srv/mongodb/rs0-0 --replSet rs0 --smallfiles --oplogSize 128

    Second member:

      mongod --port 27018 --dbpath /srv/mongodb/rs0-1 --replSet rs0 --smallfiles --oplogSize 128

    Third member:

      mongod --port 27019 --dbpath /srv/mongodb/rs0-2 --replSet rs0 --smallfiles --oplogSize 128

    The --smallfiles and --oplogSize settings reduce the disk space that each mongod instance uses. Use these options only for development !

  3. Connect to one of your mongod instances through the mongo shell. You will need to indicate which instance by specifying its port number. For the sake of simplicity and clarity, you may want to choose the first one, as in the following command:

     mongo --port 27017
  4. Use rs.initiate() to initiate the replica set.

  5. In the mongo shell connected to the primary, add the second and third mongod instances to the replica set using the rs.add() method.


rs.status() return the replica set status.

rs.conf() return the replica set configuration.

Deploy replica set

Deploy replica set for testing

Sharding (Sharded cluster)

  1. Create data directories for each of the three config server instances.

    mkdir /data/configdb
  2. Start a config server instance. (In production deployments, you must deploy exactly three config server instances.)

    mongod --configsvr --dbpath /data/configdb --port 27019
  3. Start a mongos instance.

    mongos --configdb config_server_hostnames


    mongos --configdb,,
  4. Start all shards (each shard is a replica set).

  5. Connect to mongos instance.

    mongo --port 27017
  6. Add each shard to the cluster using the sh.addShard() method.

    sh.addShard( "rs0/" )
  7. Specifying the name of the database for which to enable sharding.


sh.status() return the sharded cluster status.

For configure shard key, please read the official documentation.

Deploy shard cluster

, , , , , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>