To create a MongoDB sharded cluster, follow these steps:
Prepare the Infrastructure:
Deploy Config Servers (Replica Set):
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
rs.initiate({
_id: "configReplSet",
configsvr: true,
members: [
{ _id: 0, host: "host1:27019" },
{ _id: 1, host: "host2:27020" },
{ _id: 2, host: "host3:27021" }
]
})
Deploy Shard Servers (Replica Sets):
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
rs.initiate({
_id: "shardReplSet",
members: [
{ _id: 0, host: "host4:27018" },
{ _id: 1, host: "host5:27017" },
{ _id: 2, host: "host6:27016" }
]
})
Start mongos Routers:
mongos --configdb configReplSet/host1:27019,host2:27020,host3:27021 --port 27017
Add Shards to the Cluster:
sh.addShard("shardReplSet/host4:27018,host5:27017,host6:27016")
Enable Sharding for a Database and Collection:
sh.enableSharding("myDatabase")
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.