Bird
Raised Fist0
MongoDBquery~5 mins

Election process concept in MongoDB - Time & Space Complexity

Choose your learning style10 modes available
Time Complexity: Election process concept
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n candidates)Approx. Operations
10Counting votes 10 times
100Counting votes 100 times
1000Counting votes 1000 times

Pattern observation: The work grows directly with the number of candidates. More candidates mean more vote counts to do.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the number of candidates grows.

Common Mistake

[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.

Interview Connect

Understanding how work grows with data size helps you explain your code clearly and shows you think about efficiency in real projects.

Self-Check

"What if we stored the vote counts inside each candidate document instead of counting every time? How would the time complexity change?"

Practice

(1/5)
1. What is the main purpose of an election in a MongoDB replica set?
easy
A. To select a primary server that manages writes
B. To delete old data from the database
C. To backup the database automatically
D. To create new collections in the database

Solution

  1. Step 1: Understand the role of election in MongoDB

    In a replica set, election chooses a primary server to handle write operations.
  2. Step 2: Identify the correct purpose

    The primary server manages writes and coordinates data replication.
  3. Final Answer:

    To select a primary server that manages writes -> Option A
  4. Quick Check:

    Election = select primary server [OK]
Hint: Election picks the primary server for writes [OK]
Common Mistakes:
  • Thinking election deletes data
  • Confusing election with backup process
  • Believing election creates collections
2. Which MongoDB command shows the current election status in a replica set?
easy
A. db.showElection()
B. db.electionStatus()
C. rs.status()
D. rs.election()

Solution

  1. Step 1: Recall the command to check replica set status

    The command rs.status() shows detailed replica set info including election status.
  2. Step 2: Verify other options

    Other commands like db.showElection() or rs.election() do not exist in MongoDB.
  3. Final Answer:

    rs.status() -> Option C
  4. Quick Check:

    Check election with rs.status() [OK]
Hint: Use rs.status() to see election info [OK]
Common Mistakes:
  • Using non-existent commands
  • Confusing db commands with rs commands
  • Trying to use election-specific commands that don't exist
3. Given the following output from rs.status(), which member is currently the primary?
{
  "members": [
    {"_id": 0, "stateStr": "SECONDARY"},
    {"_id": 1, "stateStr": "PRIMARY"},
    {"_id": 2, "stateStr": "SECONDARY"}
  ]
}
medium
A. Member with _id 0
B. No primary elected yet
C. Member with _id 2
D. Member with _id 1

Solution

  1. Step 1: Read the stateStr values for each member

    Member with _id 1 has stateStr "PRIMARY", others are "SECONDARY".
  2. Step 2: Identify the primary member

    The member with stateStr "PRIMARY" is the current primary server.
  3. Final Answer:

    Member with _id 1 -> Option D
  4. Quick Check:

    Primary = stateStr "PRIMARY" member [OK]
Hint: Primary member has stateStr 'PRIMARY' in rs.status() [OK]
Common Mistakes:
  • Choosing a secondary member
  • Assuming no primary if unsure
  • Ignoring the stateStr field
4. You run rs.status() but get an error: not authorized on admin to execute command. What is the likely cause?
medium
A. You lack proper user permissions to run rs.status()
B. You are not connected to the primary server
C. The replica set is not initialized
D. The command rs.status() is misspelled

Solution

  1. Step 1: Understand the error message

    The error says 'not authorized', meaning permission is denied.
  2. Step 2: Match error to cause

    Lack of user permissions to run the command causes this error, not connection or spelling issues.
  3. Final Answer:

    You lack proper user permissions to run rs.status() -> Option A
  4. Quick Check:

    Authorization error = permission issue [OK]
Hint: Authorization errors mean missing user permissions [OK]
Common Mistakes:
  • Assuming connection problem
  • Thinking replica set not initialized
  • Blaming command spelling
5. In a MongoDB replica set with 5 members, what minimum number of votes is needed to elect a primary during an election?
hard
A. 2 votes
B. 3 votes
C. 4 votes
D. 5 votes

Solution

  1. Step 1: Recall election voting rules in MongoDB

    Primary election requires a majority of votes from members.
  2. Step 2: Calculate majority for 5 members

    Majority is more than half, so 3 out of 5 votes are needed.
  3. Final Answer:

    3 votes -> Option B
  4. Quick Check:

    Majority of 5 = 3 votes [OK]
Hint: Majority votes needed: half members + 1 [OK]
Common Mistakes:
  • Choosing half votes instead of majority
  • Thinking all members must vote
  • Confusing votes with number of members
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard