A MongoDB replica set is a group of MongoDB servers that maintain the same data set, providing redundancy and high availability. Setting up and configuring a replica set involves the following steps:
1. Install MongoDB: The first step is to install MongoDB on each server that will be a member of the replica set. The installation process will vary depending on the operating system and distribution.
2. Configure the MongoDB instances: Once MongoDB is installed, each instance needs to be configured with a unique hostname or IP address, and a common replica set name. This can be done by editing the mongod.conf configuration file, which is typically located in the /etc/mongodb/ directory on Linux systems.
3. Initialize the replica set: To initialize the replica set, choose one of the MongoDB instances to be the primary member, and then connect to it using the mongo shell. Use the rs.initiate() function to create a new replica set, specifying the hostname or IP address of each member, along with their corresponding port numbers. For example, the following command can be used to initialize a three-member replica set with members listening on ports 27017, 27018, and 27019:
> rs.initiate( {
_id : "myreplica",
members: [
{ _id: 0, host: "mongo1.example.net:27017" },
{ _id: 1, host: "mongo2.example.net:27018" },
{ _id: 2, host: "mongo3.example.net:27019" }
]
})
4. Add members to the replica set: After the replica set is initialized, additional members can be added to it using the rs.add() function. This function requires the hostname or IP address of the new member, along with its corresponding port number. For example, the following command can be used to add a new member listening on port 27020:
> rs.add("mongo4.example.net:27020")
5. Monitor the replica set: Finally, it is important to monitor the health and status of the replica set to ensure that it is providing high availability and redundancy. This can be done using the rs.status() function and the MongoDB log files.
In summary, setting up and configuring a MongoDB replica set for high availability involves installing MongoDB on each server, configuring the MongoDB instances, initializing the replica set, adding members to the replica set, and monitoring the replica set for health and status.