Hash-based sharding in MongoDB - Time & Space Complexity
When using hash-based sharding in MongoDB, we want to understand how the time to find or store data changes as the database grows.
We ask: How does the number of operations grow when we add more data?
Analyze the time complexity of this hash-based shard key lookup.
// Assume a collection sharded by hashed _id
const shardKey = hashFunction(document._id);
const shard = findShardForKey(shardKey);
const result = db.collection.find({ _id: document._id });
This code finds the shard by hashing the document's _id, then queries that shard for the document.
Look for repeated steps that affect performance.
- Primary operation: Hashing the shard key and locating the shard.
- How many times: Once per query or insert operation.
As the number of documents grows, the hash function still runs once per operation, and the shard lookup remains quick.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | ~1 hash + 1 shard lookup |
| 100 | ~1 hash + 1 shard lookup |
| 1000 | ~1 hash + 1 shard lookup |
Pattern observation: The number of operations stays about the same no matter how big the data is.
Time Complexity: O(1)
This means each query or insert takes about the same time regardless of how much data there is.
[X] Wrong: "Hash-based sharding slows down as data grows because it has to check many shards."
[OK] Correct: The hash function directly points to the correct shard, so only one shard is checked, keeping the operation fast.
Understanding how hash-based sharding keeps queries fast helps you explain how large databases stay efficient as they grow.
"What if we changed from hash-based sharding to range-based sharding? How would the time complexity change?"
Practice
What is the main purpose of hash-based sharding in MongoDB?
Solution
Step 1: Understand hash-based sharding concept
Hash-based sharding uses a hash function on the shard key to distribute data evenly.Step 2: Compare options with concept
Only To evenly distribute data across shards using a hash function describes even distribution using hashing, which matches the concept.Final Answer:
To evenly distribute data across shards using a hash function -> Option DQuick Check:
Hash-based sharding = even data distribution [OK]
- Confusing hash-based with range-based sharding
- Thinking it sorts data on shards
- Mixing sharding with replication
Which of the following is the correct way to create a hashed shard key on the field userId in MongoDB?
sh.shardCollection("mydb.users", { ??? })Solution
Step 1: Recall syntax for hashed shard key
MongoDB requires the shard key field to be set to "hashed" as a string to enable hash-based sharding.Step 2: Match options with syntax
Only { userId: "hashed" } uses the correct syntax: { userId: "hashed" }.Final Answer:
{ userId: "hashed" } -> Option BQuick Check:
Hashed shard key syntax = { field: "hashed" } [OK]
- Using 1 or -1 instead of "hashed"
- Using boolean true instead of string
- Omitting quotes around hashed
Given a collection sharded by { userId: "hashed" }, which shard will store the document { userId: 42, name: "Alice" }?
Assume the hash function maps 42 to a hash value that falls into shard 2's range.
Solution
Step 1: Understand hashed shard key routing
Documents are routed to shards based on the hash of the shard key value.Step 2: Use given hash mapping
The problem states the hash of 42 falls into shard 2's range, so the document goes to shard 2.Final Answer:
Shard 2 -> Option AQuick Check:
Hash value maps to shard 2 [OK]
- Assuming shard based on userId value directly
- Choosing 'Cannot determine' when info is given
- Confusing shard ranges with key values
Consider this command to shard a collection:
sh.shardCollection("mydb.orders", "orderId: hashed")After running this, you get an error: "Error: shard key must be an object". What is the likely cause?
Solution
Step 1: Check shardCollection syntax
The shard key must be an object specifying the field and type, e.g., { orderId: "hashed" }.Step 2: Identify error cause
The error says shard key must be an object, so likely the argument passed was not an object but a string or other type.Final Answer:
The shard key argument must be an object, but a string was passed -> Option AQuick Check:
Shard key must be an object [OK]
- Passing shard key as string instead of object
- Confusing shard key with database name
- Ignoring error message details
You want to shard a collection by email using hash-based sharding. However, you notice some shards have much more data than others. What could be a reason for this uneven distribution?
Solution
Step 1: Understand hash-based sharding behavior
Hash-based sharding usually distributes data evenly unless many documents share the same shard key value.Step 2: Analyze cause of uneven data
If many documents have the same email, their hash is the same, so they go to the same shard, causing imbalance.Final Answer:
The email field has many duplicate values causing hash collisions -> Option CQuick Check:
Duplicate keys cause uneven shard data [OK]
- Assuming hash sharding always balances perfectly
- Confusing range-based with hash-based sharding
- Ignoring data distribution of shard key values
Ready to prove it?
Pass the test and this pattern moves unknown
