Search code examples
mongodbmongodb-replica-set

MongoDB - how to set cluster?


My OS = Windows 10.

I have installed 2 MongoDB servers (Community Ed.) on 2 machines in LAN. How can I set cluster (replica, shards) using these 2 MongoDB?


Solution

  • You can follow the step by step replicaSet guide here

    Or the step by step for sharded cluster here

    I assume this is test replicaSet configuration you need in your local network , then you can follow this steps ( attention no security and no configuration files , just a test replicaSet the easiest way ) :

    1. Create data folder:

      server 1: mkdir \data1 \data2

      server 2: mkdir \data3

    2. Start the mongod services and make sure the ports are not blocked in your windows firewall:

      server 1: mongod --replSet rs0 --port 27017 --bind_ip localhost,<hostnames ad/or ip address> --dbpath \data1

      server 1: mongod --replSet rs0 --port 27018 --bind_ip localhost,<hostnames ad/or ip address> --dbpath \data2

      server 2: mongod --replSet rs0 --port 27019 --bind_ip localhost,<hostnames ad/or ip address> --dbpath \data3

    3. Access to the first member via mongo shell:

      mongosh --port 27017

    4. Init the replicaSet:

      rs.initiate({_id:"rs0",members:[{_id:0,host:":27017" }]})

    ( execute the command from the shell )

     PRIMARY>
    

    ( wait until the member elect him self as PRIMARY , the shell prompt will change as shown )

    1. Add the other two members:

      PRIMARY> rs.add("host2:port2")

      PRIMARY> rs.add("host3:port3")

    2. Check the status:

      rs.status() Now you need to see 3x members ( 2x in host1 & 1x in host2 )