0
0
MongoDBquery~5 mins

Replica set architecture mental model in MongoDB

Choose your learning style9 modes available
Introduction

A replica set in MongoDB helps keep your data safe and available by making copies of your data on multiple servers.

You want your database to keep working even if one server stops.
You need to protect your data from being lost.
You want to spread read requests to different servers to make things faster.
You want automatic failover so your app keeps running without manual fixes.
Syntax
MongoDB
rs.initiate()
rs.add("hostname:port")
rs.status()

rs.initiate() starts a new replica set.

rs.add() adds a new member to the replica set.

Examples
Starts a new replica set with the current server as the primary.
MongoDB
rs.initiate()
Adds a second server to the replica set to hold a copy of the data.
MongoDB
rs.add("mongodb2.example.net:27017")
Shows the current state of the replica set members.
MongoDB
rs.status()
Sample Program

This example starts a replica set, adds a second server, and then shows the status of all members.

MongoDB
rs.initiate()
rs.add("mongodb2.example.net:27017")
rs.status()
OutputSuccess
Important Notes

One member is the primary that accepts writes.

Other members are secondaries that copy data from the primary.

If the primary fails, one secondary automatically becomes the new primary.

Summary

A replica set keeps copies of your data on multiple servers.

It helps your database stay available and safe.

MongoDB automatically manages which server is primary and which are secondaries.