Technology Encyclopedia Home >How to create a MongoDB sharded cluster?

How to create a MongoDB sharded cluster?

To create a MongoDB sharded cluster, follow these steps:

  1. Prepare the Infrastructure:

    • Set up multiple servers or VMs for the components: shard servers, config servers, and mongos routers.
    • Ensure network connectivity between them.
  2. Deploy Config Servers (Replica Set):

    • Config servers store metadata for the cluster. Deploy them as a replica set (recommended 3 nodes).
    • Example: Start 3 config servers on ports 27019, 27020, 27021:
      mongod --configsvr --replSet configReplSet --dbpath /data/configdb1 --port 27019
      mongod --configsvr --replSet configReplSet --dbpath /data/configdb2 --port 27020
      mongod --configsvr --replSet configReplSet --dbpath /data/configdb3 --port 27021
      
    • Initialize the replica set:
      rs.initiate({
        _id: "configReplSet",
        configsvr: true,
        members: [
          { _id: 0, host: "host1:27019" },
          { _id: 1, host: "host2:27020" },
          { _id: 2, host: "host3:27021" }
        ]
      })
      
  3. Deploy Shard Servers (Replica Sets):

    • Each shard should be a replica set (minimum 3 nodes per shard for high availability).
    • Example: Start a shard replica set on ports 27018, 27017, 27016:
      mongod --shardsvr --replSet shardReplSet --dbpath /data/shard1 --port 27018
      mongod --shardsvr --replSet shardReplSet --dbpath /data/shard2 --port 27017
      mongod --shardsvr --replSet shardReplSet --dbpath /data/shard3 --port 27016
      
    • Initialize the replica set:
      rs.initiate({
        _id: "shardReplSet",
        members: [
          { _id: 0, host: "host4:27018" },
          { _id: 1, host: "host5:27017" },
          { _id: 2, host: "host6:27016" }
        ]
      })
      
  4. Start mongos Routers:

    • mongos acts as the query router. Deploy at least one (multiple for redundancy).
    • Example: Start mongos on port 27017:
      mongos --configdb configReplSet/host1:27019,host2:27020,host3:27021 --port 27017
      
  5. Add Shards to the Cluster:

    • Connect to a mongos instance and add shards:
      sh.addShard("shardReplSet/host4:27018,host5:27017,host6:27016")
      
  6. Enable Sharding for a Database and Collection:

    • Enable sharding on a database:
      sh.enableSharding("myDatabase")
      
    • Choose a shard key and shard the collection:
      sh.shardCollection("myDatabase.myCollection", { "shardKeyField": 1 })
      

For production, use Tencent Cloud Database for MongoDB to simplify deployment, scaling, and management. It provides automated sharding, backups, and high availability.