0
0
MongoDBquery~5 mins

Automatic failover behavior in MongoDB

Choose your learning style9 modes available
Introduction
Automatic failover helps keep your database working even if one server stops. It switches to a backup server without you needing to do anything.
When you want your app to keep working even if a database server crashes.
When you have multiple database servers and want one to take over if the main one fails.
When you want to avoid downtime during server problems.
When you want your database to be reliable and always available.
When you want to protect your data by having copies on different servers.
Syntax
MongoDB
Automatic failover is not a command but a feature of MongoDB replica sets.
You set up a replica set with multiple members.
If the primary member fails, the replica set automatically elects a new primary.
Replica sets are groups of MongoDB servers that keep copies of the same data.
Failover happens automatically without needing manual intervention.
Examples
This command starts a replica set on your MongoDB server.
MongoDB
rs.initiate()
// Starts a replica set with the current server as primary
Adds another server to the replica set to help with failover.
MongoDB
rs.add("mongodb1.example.net:27017")
// Adds a new member to the replica set
You can check which server is primary and which are secondaries.
MongoDB
rs.status()
// Shows the current status of the replica set
Sample Program
This sets up a replica set with three members on different ports of localhost. Automatic failover will happen if the primary server stops.
MongoDB
rs.initiate({
  _id: "rs0",
  members: [
    { _id: 0, host: "localhost:27017" },
    { _id: 1, host: "localhost:27018" },
    { _id: 2, host: "localhost:27019" }
  ]
})

// After this, if the primary at localhost:27017 fails,
// MongoDB will automatically elect one of the other members as primary.
OutputSuccess
Important Notes
Automatic failover works best if you have at least three members in your replica set.
The election process usually takes a few seconds, so there might be a short delay during failover.
Make sure your application handles reconnection to the new primary after failover.
Summary
Automatic failover keeps your database available by switching to a backup server if the main one fails.
It works by using MongoDB replica sets with multiple members.
You do not need to manually switch servers; MongoDB handles it for you.