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?
Other Common MongoDB Performance Questions (and Answers)
- How to improve MongoDB query performance?
- How to check MongoDB replication status?
- How do you connect to a MongoDB cluster?
- How do you clear the cache in MongoDB?
- How many connections can MongoDB handle?
- How does MongoDB sharding work?
- How to check MongoDB cluster status?
- How to change a MongoDB cluster password?
- How to create a MongoDB cluster?
- How to restart a MongoDB cluster?
- How do I reset my MongoDB cluster password?
- How does the $in operator affect performance in MongoDB?
Free System Design on AWS E-Book
Download this early release of O'Reilly's latest cloud infrastructure e-book: System Design on AWS.
Switch & save up to 80%
Dragonfly is fully compatible with the Redis ecosystem and requires no code changes to implement. Instantly experience up to a 25X boost in performance and 80% reduction in cost