กลยุทธ์การแบ่งส่วนแบบช่วงเทียบกับแบบแฮช
ผู้เรียนจะกำหนดค่าคอลเลกชันด้วยการแบ่งส่วนแบบช่วงสำหรับการค้นหาแบบช่วง หรือแบบแฮชสำหรับการกระจายการเขียนอย่างสม่ำเสมอ และเปรียบเทียบข้อแลกเปลี่ยนของทั้งสองแบบ
กลยุทธ์การแบ่งส่วนแบบช่วงเทียบกับแบบแฮช เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Two Sharding Strategies Compared
MongoDB supports two built-in sharding strategies: ranged sharding and hashed sharding. Ranged sharding assigns contiguous ranges of shard key values to specific shards; hashed sharding applies a hash function to the key first and distributes based on the hash. Both have distinct strengths, and the right choice depends on your data access patterns.
Ranged Sharding: How It Works
In ranged sharding, MongoDB divides the shard key's value space into contiguous ranges and assigns each range (chunk) to a shard. For example, users with userId 1–10,000 go to shard A, 10,001–20,000 to shard B, and so on. Documents with nearby shard key values are co-located on the same shard, which is ideal for range queries.
// Enable ranged sharding on a field
sh.shardCollection('mydb.products', { category: 1, price: 1 })
// Range query is now targeted to the shard(s) holding that range
db.products.find({ category: 'electronics', price: { $lt: 100 } })Ranged Sharding: Strengths
Ranged sharding excels when your application frequently queries ranges of values: date ranges, price ranges, alphabetical name ranges, or paginated results sorted by a numeric ID. Because adjacent values are co-located, range queries become targeted queries that touch only one or a few shards, keeping latency low.
// With ranged sharding on { orderId: 1 }, this is targeted:
db.orders.find({
orderId: { $gte: 50000, $lte: 60000 }
})
// mongos knows exactly which shard owns this rangeRanged Sharding: Weakness — Hot Spots
The critical weakness of ranged sharding is write hot spots when the shard key is monotonically increasing (timestamps, auto-increment IDs, ObjectId). All new documents cluster at the high end of the range and land on one shard. Until the balancer migrates chunks, this shard absorbs all write traffic while other shards sit idle.
// Problematic: all new events go to the max-range shard
sh.shardCollection('mydb.events', { createdAt: 1 }) // ranged, monotonic = hot spot
// Production symptom: one shard has 90%+ of recent data
// and absorbs all write IOPSHashed Sharding: How It Works
In hashed sharding, MongoDB computes a hash of the shard key value and uses the hash to determine the chunk. Documents are distributed based on hash values, which appear random even if the original keys are monotonically increasing. This guarantees a near-uniform initial write distribution across all shards.
// Hashed sharding on _id (neutralizes ObjectId monotonicity)
sh.shardCollection('mydb.events', { _id: 'hashed' })
// Hashed sharding on userId
sh.shardCollection('mydb.sessions', { userId: 'hashed' })Hashed Sharding: Strengths
Hashed sharding is the best choice when your primary goal is uniform write distribution across shards and you do not need range queries on the shard key. It is ideal for high-insert-rate workloads with monotonic keys (event logs, IoT sensor data, messaging) where every shard should absorb an equal share of write traffic.
// With hashed sharding, inserts are spread uniformly:
// doc1 (hash: 2345...) -> shard A
// doc2 (hash: 8901...) -> shard C
// doc3 (hash: 4567...) -> shard B
// No hot spot regardless of insert orderHashed Sharding: Weakness — No Range Efficiency
The trade-off of hashed sharding is that range queries on the shard key become scatter-gather. Because adjacent hash values are scattered across shards, a query like { createdAt: { $gte: t1, $lte: t2 } } must fan out to all shards. If range queries are frequent and latency-sensitive, hashed sharding may negate the performance gains from sharding.
// With hashed sharding on createdAt:
// Range query CANNOT be targeted — fans out to all shards
db.events.find({ createdAt: { $gte: ISODate('2025-01-01'), $lte: ISODate('2025-02-01') } })
// Equivalent to a full collection scan across all shardsChoosing Between Ranged and Hashed
Decision guide: Ranged sharding → your shard key has natural distribution (not monotonic) AND your top queries are range queries on that key. Hashed sharding → your shard key is monotonic OR your top queries are point lookups (equality) on a high-cardinality field. When in doubt and inserts are the bottleneck, prefer hashed.
Hybrid: Compound Key With Hashed Component
You can combine both strategies with a compound shard key where the first field is ranged and gives query affinity, while adding a hashed second field spreads the load within each range. Example: { tenantId: 1, _id: 'hashed' } co-locates data by tenant for targeted queries while distributing writes across shards within each tenant.
// Ranged tenantId + hashed _id within tenant
// Writes are distributed; per-tenant queries are targeted
sh.shardCollection('mydb.events', { tenantId: 1, _id: 'hashed' })
// Targeted: all tenantId queries go to the right shard(s)
db.events.find({ tenantId: 'acme', _id: ObjectId('...') })Checking Which Strategy Is Active
You can inspect a collection's sharding configuration to determine which strategy is in use. The config server metadata stores the shard key and whether it uses 'hashed'. The sh.status() command and db.collection.stats() both expose this information.
// Check sharding info for a collection
use config
db.collections.findOne({ _id: 'mydb.events' })
// { key: { _id: 'hashed' }, unique: false, ... }
// Or via sh.status()
sh.status()Pre-Splitting Chunks for Bulk Loads
When bulk-loading data into a freshly sharded collection, all chunks initially live on one shard and must be migrated by the balancer — which can be slow. Pre-splitting creates an initial set of empty chunks distributed across all shards before loading. This ensures the balancer's work is minimised and writes are spread from the first insert.
// Pre-split chunks for ranged sharding
// Define desired split points and assign to shards
db.adminCommand({ split: 'mydb.events', middle: { userId: 500000 } })
db.adminCommand({ moveChunk: 'mydb.events',
find: { userId: 500000 }, to: 'shard02' })Quick Check
Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.
Lesson Recap
In this lesson you learned: ranged sharding co-locates similar key values for efficient range queries but creates hot spots with monotonic keys, hashed sharding distributes uniformly across shards but makes range queries scatter-gather, and compound keys can combine both benefits. Next up we explore zone sharding for pinning data to specific regions.
เรียนรู้ JavaScript ด้วย AI tutor — ฟรี
เขียนและเรียกใช้โค้ดจริงในเบราว์เซอร์ของคุณ รับความช่วยเหลือทันทีจาก AI tutor 24/7 และเรียนรู้ต่อจากที่คุณหยุดบนเว็บหรือในแอป
- คอร์ส
- 30
- บทเรียน
- 120
คำถามที่พบบ่อย
บทเรียน “กลยุทธ์การแบ่งส่วนแบบช่วงเทียบกับแบบแฮช” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “กลยุทธ์การแบ่งส่วนแบบช่วงเทียบกับแบบแฮช” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส MongoDB Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “กลยุทธ์การแบ่งส่วนแบบช่วงเทียบกับแบบแฮช”
ผู้เรียนจะกำหนดค่าคอลเลกชันด้วยการแบ่งส่วนแบบช่วงสำหรับการค้นหาแบบช่วง หรือแบบแฮชสำหรับการกระจายการเขียนอย่างสม่ำเสมอ และเปรียบเทียบข้อแลกเปลี่ยนของทั้งสองแบบ คุณปฏิบัติ MongoDB Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน MongoDB Academy หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน MongoDB Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “กลยุทธ์การแบ่งส่วนแบบช่วงเทียบกับแบบแฮช” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม
ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- แนวคิดการแบ่งส่วน: ชังก์ ตัวปรับสมดุล และคีย์ชาร์ด
- การเลือกคีย์ชาร์ด: ความหลากหลาย ความถี่ ความเป็นโมโนโทน
- กลยุทธ์การแบ่งส่วนแบบช่วงเทียบกับแบบแฮช
- การแบ่งส่วนตามโซน: การตรึงข้อมูลไว้ในภูมิภาค