0
0
MongoDBquery~5 mins

Replica set configuration basics in MongoDB

Choose your learning style9 modes available
Introduction

A replica set keeps copies of your data on multiple servers. This helps your data stay safe and available even if one server stops working.

You want your database to keep working even if one server crashes.
You want to make sure your data is backed up automatically on other servers.
You want to read data from different servers to balance the load.
You want to upgrade or fix one server without stopping the whole database.
You want to protect your data from hardware failures.
Syntax
MongoDB
rs.initiate(configuration)

// configuration is an object that defines members and settings

The rs.initiate() command starts the replica set with your settings.

The configuration object includes a list of members (servers) with their IDs and addresses.

Examples
This simple command creates a replica set with just the current server as the only member.
MongoDB
rs.initiate()
// Starts a replica set with default settings and one member (the current server)
This command creates a replica set named rs0 with three members running on different ports.
MongoDB
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "localhost:27017" },
    { _id: 1, host: "localhost:27018" },
    { _id: 2, host: "localhost:27019" }
  ]
})
Sample Program

This command sets up a replica set called myReplicaSet with two members on localhost ports 27017 and 27018.

MongoDB
rs.initiate({
  _id: "myReplicaSet",
  members: [
    { _id: 0, host: "localhost:27017" },
    { _id: 1, host: "localhost:27018" }
  ]
})
OutputSuccess
Important Notes

Each member in the replica set must have a unique _id number starting from 0.

The host field must include the server address and port.

After initiating, use rs.status() to check the replica set health.

Summary

A replica set is a group of MongoDB servers that keep copies of the same data.

You configure it using rs.initiate() with a list of members.

This setup helps keep your data safe and your database available.