0
0
MongodbHow-ToBeginner · 3 min read

How to Check Replica Set Status in MongoDB Quickly

To check the status of a MongoDB replica set, use the rs.status() command in the MongoDB shell. This command returns detailed information about the replica set members, their states, and health.
📐

Syntax

The rs.status() command is run inside the MongoDB shell connected to a replica set member. It returns a document describing the current state of the replica set.

  • rs.status(): Returns the status of the replica set.
mongodb
rs.status()
💻

Example

This example shows how to connect to a MongoDB replica set member using the shell and run rs.status() to get the replica set status.

mongodb
mongo --host yourReplicaSetHost

> rs.status()
Output
{ "set" : "rs0", "date" : ISODate("2024-06-01T12:00:00Z"), "myState" : 1, "members" : [ { "_id" : 0, "name" : "mongo1:27017", "state" : 1, "stateStr" : "PRIMARY", "uptime" : 3600, "health" : 1 }, { "_id" : 1, "name" : "mongo2:27017", "state" : 2, "stateStr" : "SECONDARY", "uptime" : 3500, "health" : 1 } ] }
⚠️

Common Pitfalls

Common mistakes when checking replica set status include:

  • Running rs.status() on a standalone MongoDB instance instead of a replica set member, which returns an error.
  • Not connecting to the correct host or port of a replica set member.
  • Misinterpreting the state codes; for example, 1 means PRIMARY, 2 means SECONDARY.
mongodb
/* Wrong: Running on standalone instance */
rs.status()
// Error: not running with --replSet

/* Right: Connect to replica set member first */
mongo --host mongo1:27017
> rs.status()
📊

Quick Reference

FieldDescription
setName of the replica set
myStateCurrent member state code (1=PRIMARY, 2=SECONDARY, etc.)
membersArray of replica set members with their status
stateStrReadable state name of each member
healthHealth status (1=healthy, 0=unhealthy)

Key Takeaways

Use rs.status() in the MongoDB shell to check replica set status.
Connect to a replica set member, not a standalone instance, before running rs.status().
Understand the state codes: 1 means PRIMARY, 2 means SECONDARY.
The output shows member health, uptime, and roles in the replica set.
Common errors happen if you run the command on a non-replica set MongoDB.