# 1 turining on the database

sudo systemctl start mongod



# 2 creating folder for storing information

mkdir -p data/config data/s1n1 data/s1n2 data/s2n1 data/s2n2


# Start Config Server (Replica Set):


mongod --configsvr --replSet cfgrs --port 27016 --dbpath ./data/config --bind_ip localhost
# Connect via mongosh and run: rs.initiate({_id: "cfgrs", members: [{_id: 0, host: "localhost:27016"}]})




# Start Shard 1 (Replica Set - 2 members):

mongod --shardsvr --replSet s1rs --port 27017 --dbpath ./data/s1n1 --bind_ip localhost
mongod --shardsvr --replSet s1rs --port 27018 --dbpath ./data/s1n2 --bind_ip localhost
# Connect to 27017 and run: rs.initiate({_id: "s1rs", members: [{_id: 0, host: "localhost:27017"}, {_id: 1, host: "localhost:27018"}]})


#Start Shard 2 (Replica Set - 2 members):


mongod --shardsvr --replSet s2rs --port 27019 --dbpath ./data/s2n1 --bind_ip localhost
mongod --shardsvr --replSet s2rs --port 27020 --dbpath ./data/s2n2 --bind_ip localhost
# Connect to 27019 and run: rs.initiate({_id: "s2rs", members: [{_id: 0, host: "localhost:27019"}, {_id: 1, host: "localhost:27020"}]})



#Start Mongos (Router):

mongos --configdb cfgrs/localhost:27016 --port 27021 --bind_ip localhost


#Configure Sharding in MongoDB
#Connect to the router (mongosh --port 27021) and run:

#  Add Shards to the cluster
sh.addShard("s1rs/localhost:27017");
sh.addShard("s2rs/localhost:27019");

#  Enable sharding for the database
sh.enableSharding("videodb");

#  Shard the Movies collection (Range-based on title)
use videodb;
db.movies.createIndex({ title: 1 });
sh.shardCollection("videodb.movies", { title: 1 });

#  Shard the Users collection (Hashed on _id)
sh.shardCollection("videodb.users", { _id: "hashed" });
