0
0
MongoDBquery~30 mins

Primary and secondary nodes in MongoDB - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Primary and Secondary Nodes in MongoDB Replica Set
📖 Scenario: You are managing a MongoDB replica set for a small online store. The replica set has one primary node and two secondary nodes. You want to understand how to identify the primary and secondary nodes using MongoDB queries.
🎯 Goal: Learn to query the replica set status to find which node is primary and which are secondary nodes.
📋 What You'll Learn
Create a variable called replicaSetStatus that stores the output of rs.status().
Create a variable called primaryNode to store the primary node's name from replicaSetStatus.
Create a list called secondaryNodes that contains the names of all secondary nodes from replicaSetStatus.
Add a final statement to show the replica set members with their roles.
💡 Why This Matters
🌍 Real World
Replica sets in MongoDB provide high availability and data redundancy. Knowing how to identify primary and secondary nodes helps in monitoring and managing the database cluster.
💼 Career
Database administrators and backend developers often need to check replica set status to troubleshoot issues or optimize read/write operations.
Progress0 / 4 steps
1
Get Replica Set Status
Create a variable called replicaSetStatus and assign it the result of rs.status() to get the current status of the replica set.
MongoDB
Need a hint?

Use rs.status() to get the replica set status and assign it to replicaSetStatus.

2
Identify the Primary Node
Create a variable called primaryNode and assign it the name of the member whose stateStr is "PRIMARY" from replicaSetStatus.members.
MongoDB
Need a hint?

Use a generator expression to find the member with stateStr equal to "PRIMARY".

3
List All Secondary Nodes
Create a list called secondaryNodes that contains the name of all members whose stateStr is "SECONDARY" from replicaSetStatus.members.
MongoDB
Need a hint?

Use a list comprehension to collect all members with stateStr equal to "SECONDARY".

4
Show Replica Set Members and Roles
Create a variable called membersWithRoles that is a list of dictionaries. Each dictionary should have keys name and role, where role is the stateStr of the member from replicaSetStatus.members.
MongoDB
Need a hint?

Use a list comprehension to create dictionaries with name and role for each member.