Bird
Raised Fist0
MongoDBquery~10 mins

Range-based sharding in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Range-based sharding
Start: Insert Document
↓
Extract Shard Key Value
↓
Compare Value to Ranges
↓
Find Matching Shard Range
↓
Route Document to Shard
↓
Store Document in Shard
↓
End
Documents are routed to shards by comparing their shard key value to defined ranges, then stored in the matching shard.
Execution Sample
MongoDB
sh.enableSharding("mydb")
sh.shardCollection("mydb.users", { age: 1 })
// Define ranges:
// Shard1: age < 30
// Shard2: 30 <= age < 60
// Shard3: age >= 60

// Insert document {name: "Alice", age: 25}
This example enables sharding on a collection by age, defines ranges for shards, and inserts a document to be routed.
Execution Table
StepActionShard Key ValueRange CheckedShard SelectedResult
1Insert document {name: "Alice", age: 25}25age < 30Shard1Document routed to Shard1
2Insert document {name: "Bob", age: 45}4530 <= age < 60Shard2Document routed to Shard2
3Insert document {name: "Carol", age: 65}65age >= 60Shard3Document routed to Shard3
4Insert document {name: "Dave", age: 30}3030 <= age < 60Shard2Document routed to Shard2
5Insert document {name: "Eve", age: 29}29age < 30Shard1Document routed to Shard1
6No more documents---End of routing
💡 All documents routed to shards based on their age falling into defined ranges.
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
Shard Key Value-2545653029-
Shard Selected-Shard1Shard2Shard3Shard2Shard1-
Key Moments - 2 Insights
Why does the document with age 30 go to Shard2 and not Shard1?
Because the range for Shard1 is age < 30, so 30 is not included there. The range for Shard2 is 30 <= age < 60, so 30 fits in Shard2's range as shown in execution_table row 4.
What happens if a document's shard key value does not fit any defined range?
In range-based sharding, all possible values should be covered by ranges. If not, the document cannot be routed properly. This example assumes full coverage, so no such case appears in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, which shard does the document with age 65 get routed to?
AShard3
BShard1
CShard2
DNone
💡 Hint
Check row 3 in the execution_table where age 65 is routed.
At which step does the shard key value equal 30?
AStep 2
BStep 4
CStep 5
DStep 1
💡 Hint
Look at the Shard Key Value column in execution_table.
If the range for Shard1 changed to age <= 30, where would the document with age 30 be routed?
AShard3
BShard2
CShard1
DCannot be determined
💡 Hint
Consider how the range comparison changes and check the routing logic in concept_flow.
Concept Snapshot
Range-based sharding routes documents by shard key value ranges.
Define continuous, non-overlapping ranges for shards.
Insertions compare shard key to ranges to pick shard.
Example: age < 30 → Shard1, 30 ≤ age < 60 → Shard2, age ≥ 60 → Shard3.
Ensure all values fit some range to avoid routing errors.
Full Transcript
Range-based sharding in MongoDB splits data by ranges of a shard key. When a document is inserted, the system looks at the shard key value and compares it to the defined ranges. It finds which range the value fits in and sends the document to the corresponding shard. For example, if the shard key is age, and ranges are set as age less than 30 for Shard1, age between 30 and 59 for Shard2, and age 60 or more for Shard3, then a document with age 25 goes to Shard1, age 45 to Shard2, and age 65 to Shard3. This method helps keep related data together and balances load. It is important that the ranges cover all possible values so every document can be routed correctly.

Practice

(1/5)
1. What is the main idea behind range-based sharding in MongoDB?
easy
A. Data is randomly distributed across shards.
B. Data is split into ranges based on shard key values.
C. Data is duplicated on all shards for backup.
D. Data is stored only on a single shard.

Solution

  1. Step 1: Understand range-based sharding concept

    Range-based sharding divides data into continuous ranges based on shard key values.
  2. Step 2: Compare with other options

    Random distribution or duplication are not characteristics of range-based sharding.
  3. Final Answer:

    Data is split into ranges based on shard key values. -> Option B
  4. Quick Check:

    Range-based sharding = Data split by ranges [OK]
Hint: Remember: range-based means splitting by value ranges [OK]
Common Mistakes:
  • Confusing range-based with hash-based sharding
  • Thinking data is duplicated on all shards
  • Assuming data is randomly distributed
2. Which of the following is the correct way to enable range-based sharding on a collection in MongoDB?
easy
A. sh.shardRangeCollection("db.collection", { "field": 1 })
B. sh.enableRangeSharding("db.collection")
C. db.collection.shardRange({ "field": 1 })
D. sh.shardCollection("db.collection", { "field": 1 })

Solution

  1. Step 1: Recall MongoDB sharding command

    The correct command to shard a collection by a key is sh.shardCollection() with the shard key.
  2. Step 2: Verify syntax correctness

    sh.shardCollection("db.collection", { "field": 1 }) uses the correct syntax: sh.shardCollection("db.collection", { "field": 1 }). Other options are invalid commands.
  3. Final Answer:

    sh.shardCollection("db.collection", { "field": 1 }) -> Option D
  4. Quick Check:

    Use sh.shardCollection() to enable sharding [OK]
Hint: Use sh.shardCollection() with shard key object [OK]
Common Mistakes:
  • Using non-existent commands like sh.enableRangeSharding
  • Incorrect method names like shardRangeCollection
  • Passing wrong parameters or missing shard key
3. Given a collection sharded by the field age with ranges: { age: { $lt: 20 } }, { age: { $gte: 20, $lt: 40 } }, and { age: { $gte: 40 } }, which shard will store a document with { age: 35 }?
medium
A. Shard with range { age: { $gte: 20, $lt: 40 } }
B. Shard with range { age: { $lt: 20 } }
C. Shard with range { age: { $gte: 40 } }
D. Document will be stored on all shards

Solution

  1. Step 1: Identify the correct range for age 35

    Age 35 fits in the range where age is greater or equal to 20 and less than 40.
  2. Step 2: Match the range to the shard

    The shard with range { age: { $gte: 20, $lt: 40 } } will store the document.
  3. Final Answer:

    Shard with range { age: { $gte: 20, $lt: 40 } } -> Option A
  4. Quick Check:

    35 is between 20 and 40, so goes to that shard [OK]
Hint: Match value to shard range boundaries carefully [OK]
Common Mistakes:
  • Choosing the shard with $lt: 20 incorrectly
  • Assuming document is stored on all shards
  • Confusing range boundaries (gte vs lt)
4. You have a range-based sharded collection on score with ranges: { score: { $lt: 50 } } and { score: { $gte: 50 } }. You try to insert { score: "high" } but get an error. What is the likely cause?
medium
A. The shard key ranges overlap causing conflict.
B. The shard key field is missing in the document.
C. The shard key value type does not match the defined range type.
D. MongoDB does not support string values in shard keys.

Solution

  1. Step 1: Understand shard key type requirements

    Shard key values must match the type used in range definitions. Here, ranges expect numeric scores.
  2. Step 2: Identify the error cause

    Inserting a string "high" for a numeric shard key causes a type mismatch error.
  3. Final Answer:

    The shard key value type does not match the defined range type. -> Option C
  4. Quick Check:

    Shard key types must match range types [OK]
Hint: Shard key values must match range data types [OK]
Common Mistakes:
  • Assuming missing shard key field causes this error
  • Thinking overlapping ranges cause insert errors
  • Believing MongoDB disallows strings in shard keys
5. You want to shard a large user collection by signupDate using range-based sharding. Which shard key choice will best support queries filtering users by recent signup dates?
hard
A. Use { signupDate: 1 } as shard key to split by date ranges.
B. Use { userId: 1 } as shard key for even data distribution.
C. Use { signupDate: "hashed" } to hash dates for randomness.
D. Use { lastLogin: 1 } as shard key for login-based queries.

Solution

  1. Step 1: Identify query pattern

    Queries filter users by recent signup dates, so shard key should support range queries on signupDate.
  2. Step 2: Choose shard key matching query pattern

    Using { signupDate: 1 } enables range-based sharding by date, optimizing these queries.
  3. Step 3: Evaluate other options

    Hashing or using unrelated fields won't support efficient range queries on signupDate.
  4. Final Answer:

    Use { signupDate: 1 } as shard key to split by date ranges. -> Option A
  5. Quick Check:

    Shard key matches query field for best performance [OK]
Hint: Match shard key to common query field for range queries [OK]
Common Mistakes:
  • Choosing hashed shard key when range queries are needed
  • Picking unrelated fields like userId or lastLogin
  • Ignoring query patterns when selecting shard key
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