Introducing Dragonfly Cloud! Learn More

Question: How do you list replica set members in MongoDB?

Answer

To list replica set members in MongoDB, you typically use the rs.status() method from the MongoDB shell. This command returns a document that includes information about the configuration and status of the replica set, including the details of each member.

Here's a basic way to get the list of replica set members:

rs.status().members.forEach(member => { print(`Member ID: ${member._id}, Host: ${member.name}, State: ${member.stateStr}`); });

This script iterates over the members array returned by rs.status(), printing out the ID, host (including port), and state (like PRIMARY, SECONDARY, ARBITER, etc.) of each member.

To further understand each part:

  • rs.status(): Returns a document with the current replica set status.
  • .members: Accesses the array of member information within the status document.
  • .forEach(...): Iterates over each element in the array.
  • member._id: The unique identifier of the member in the replica set.
  • member.name: Hostname and port of the member.
  • member.stateStr: A human-readable string representing the member's state.

This simple script is a great starting point for getting an overview of the replica set members directly from the MongoDB shell. For more detailed management or analysis, you may want to capture the output of rs.status() in a variable and work with it as a JavaScript object.

Was this content helpful?

White Paper

Free System Design on AWS E-Book

Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.

Free System Design on AWS E-Book

Start building today 

Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement.