Election process concept in MongoDB - Time & Space Complexity
When we look at an election process in a database, we want to know how long it takes as more candidates or voters join.
We ask: How does the work grow when the election gets bigger?
Analyze the time complexity of the following code snippet.
// Find all candidates
const candidates = db.candidates.find({});
// Count votes for each candidate
candidates.forEach(candidate => {
const voteCount = db.votes.countDocuments({ candidateId: candidate._id });
print(`Candidate ${candidate.name} has ${voteCount} votes.`);
});
This code finds all candidates and counts how many votes each one has.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each candidate and counting votes.
- How many times: Once for each candidate in the list.
Explain the growth pattern intuitively.
| Input Size (n candidates) | Approx. Operations |
|---|---|
| 10 | Counting votes 10 times |
| 100 | Counting votes 100 times |
| 1000 | Counting votes 1000 times |
Pattern observation: The work grows directly with the number of candidates. More candidates mean more vote counts to do.
Time Complexity: O(n)
This means the time to finish grows in a straight line as the number of candidates grows.
[X] Wrong: "Counting votes for all candidates is always fast and does not depend on the number of candidates."
[OK] Correct: Each candidate requires a separate count, so more candidates mean more counting work.
Understanding how work grows with data size helps you explain your code clearly and shows you think about efficiency in real projects.
"What if we stored the vote counts inside each candidate document instead of counting every time? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of election in MongoDB
In a replica set, election chooses a primary server to handle write operations.Step 2: Identify the correct purpose
The primary server manages writes and coordinates data replication.Final Answer:
To select a primary server that manages writes -> Option AQuick Check:
Election = select primary server [OK]
- Thinking election deletes data
- Confusing election with backup process
- Believing election creates collections
Solution
Step 1: Recall the command to check replica set status
The commandrs.status()shows detailed replica set info including election status.Step 2: Verify other options
Other commands likedb.showElection()orrs.election()do not exist in MongoDB.Final Answer:
rs.status() -> Option CQuick Check:
Check election with rs.status() [OK]
- Using non-existent commands
- Confusing db commands with rs commands
- Trying to use election-specific commands that don't exist
rs.status(), which member is currently the primary?
{
"members": [
{"_id": 0, "stateStr": "SECONDARY"},
{"_id": 1, "stateStr": "PRIMARY"},
{"_id": 2, "stateStr": "SECONDARY"}
]
}Solution
Step 1: Read the stateStr values for each member
Member with _id 1 has stateStr "PRIMARY", others are "SECONDARY".Step 2: Identify the primary member
The member with stateStr "PRIMARY" is the current primary server.Final Answer:
Member with _id 1 -> Option DQuick Check:
Primary = stateStr "PRIMARY" member [OK]
- Choosing a secondary member
- Assuming no primary if unsure
- Ignoring the stateStr field
rs.status() but get an error: not authorized on admin to execute command. What is the likely cause?Solution
Step 1: Understand the error message
The error says 'not authorized', meaning permission is denied.Step 2: Match error to cause
Lack of user permissions to run the command causes this error, not connection or spelling issues.Final Answer:
You lack proper user permissions to run rs.status() -> Option AQuick Check:
Authorization error = permission issue [OK]
- Assuming connection problem
- Thinking replica set not initialized
- Blaming command spelling
Solution
Step 1: Recall election voting rules in MongoDB
Primary election requires a majority of votes from members.Step 2: Calculate majority for 5 members
Majority is more than half, so 3 out of 5 votes are needed.Final Answer:
3 votes -> Option BQuick Check:
Majority of 5 = 3 votes [OK]
- Choosing half votes instead of majority
- Thinking all members must vote
- Confusing votes with number of members
Ready to prove it?
Pass the test and this pattern moves unknown
