Primary and secondary nodes in MongoDB - Time & Space Complexity
When working with MongoDB replica sets, operations can run on primary or secondary nodes.
We want to understand how the time to complete operations changes depending on which node handles them.
Analyze the time complexity of a read operation on primary vs secondary nodes.
// Read from primary node
const primaryResult = db.collection.find({}).toArray();
// Read from secondary node with read preference
const secondaryResult = db.getMongo().setReadPref('secondary').getDB('test').collection.find({}).toArray();
This code reads all documents from a collection, once from the primary and once from a secondary node.
Look for repeated work done during the read operation.
- Primary operation: Scanning all documents in the collection to return results.
- How many times: Once per read operation, scanning each document once.
As the number of documents grows, the time to read all documents grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 document reads |
| 100 | 100 document reads |
| 1000 | 1000 document reads |
Pattern observation: The time grows roughly in direct proportion to the number of documents.
Time Complexity: O(n)
This means the time to read all documents grows linearly with the number of documents.
[X] Wrong: "Reading from a secondary node is always faster than from the primary node."
[OK] Correct: Both nodes scan the same number of documents, so time depends mostly on data size, not node type. Network and replication lag can affect speed but do not change the fundamental time complexity.
Understanding how operations scale on primary and secondary nodes helps you design efficient database queries and explain trade-offs clearly in interviews.
"What if we added an index to the collection? How would the time complexity of reading documents change on primary and secondary nodes?"