MongoDB Academy · บทเรียน

การเลือกคีย์ชาร์ด: ความหลากหลาย ความถี่ ความเป็นโมโนโทน

ผู้เรียนจะประเมินตัวเลือกคีย์ชาร์ดตามสามมิติ ได้แก่ ความหลากหลาย การกระจายการเขียน และการกำหนดเป้าหมายการค้นหา และหลีกเลี่ยงรูปแบบต่อต้านชาร์ดร้อน

บทเรียน 2 จาก 413 ขั้นตอน

การเลือกคีย์ชาร์ด: ความหลากหลาย ความถี่ ความเป็นโมโนโทน เป็นบทเรียน MongoDB Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน MongoDB Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส MongoDB Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Why Shard Key Choice Is Critical

The shard key is immutable once set and cannot be changed without unsharding and re-sharding the entire collection — an expensive, disruptive operation. Choosing the wrong shard key leads to hot shards, poor query routing, and wasted hardware. You must evaluate candidates against three dimensions: cardinality, frequency, and monotonicity.

Cardinality: How Many Distinct Values?

Cardinality is the number of distinct values the shard key can take. High cardinality (e.g., userId, email, orderId) is good — it gives MongoDB many possible chunk boundaries and lets the balancer distribute data finely. Low cardinality (e.g., status: 'active' | 'inactive', country with 50 values) creates jumbo chunks that cannot be split or migrated.

// HIGH cardinality — good shard key
sh.shardCollection('mydb.users', { userId: 1 })

// LOW cardinality — avoid: only 2 chunk boundaries possible
sh.shardCollection('mydb.users', { status: 1 }) // BAD

Frequency: How Evenly Distributed Are Values?

Frequency measures how many documents share each shard key value. Even high-cardinality keys can be problematic if a small number of values appear in the vast majority of documents. For example, a countryCode field might have 200 distinct values, but 90% of users are from a single country — creating a massive hot chunk that cannot be split.

// Estimate frequency distribution before choosing
db.users.aggregate([
  { $group: { _id: '$countryCode', count: { $sum: 1 } } },
  { $sort: { count: -1 } },
  { $limit: 10 }
])
// If top 1 value has 80%+ of docs, this is a bad shard key

Monotonicity: Are Values Always Increasing?

Monotonicity refers to whether shard key values always increase (or decrease) over time. Fields like createdAt timestamps and ObjectId (_id) are monotonically increasing. This is problematic because all new inserts land on the same 'max' chunk on one shard, creating a write hot spot even when data is evenly distributed historically.

// Monotonic keys cause write hot spots
// All new orders go to the shard with the latest date range
sh.shardCollection('mydb.orders', { createdAt: 1 }) // BAD for high insert rate

// Fix: use hashed sharding to spread monotonic keys
sh.shardCollection('mydb.orders', { createdAt: 'hashed' })

Ideal Shard Key Properties Summary

The ideal shard key has: High cardinality — thousands or millions of distinct values. Low frequency skew — no single value dominates. Non-monotonic distribution — values do not always increase, or you use hashed sharding. Query alignment — matches the filters in your most frequent, latency-sensitive queries for targeted routing.

Compound Shard Keys

A compound shard key combines two fields for better distribution. For example, { tenantId: 1, createdAt: 1 } distributes across tenants (high cardinality) and allows ranged queries within each tenant. The first field determines coarse distribution; the second provides fine-grained splitting. Compound keys can satisfy multi-field query predicates as targeted queries.

// Compound shard key: tenant + date
sh.shardCollection('mydb.events', { tenantId: 1, createdAt: 1 })

// This query is fully targeted (both shard key fields present)
db.events.find({ tenantId: 't123', createdAt: { $gte: ISODate('2025-01-01') } })

Hashed Shard Keys

A hashed shard key applies a hash function to the field value before mapping it to a chunk. This converts monotonic keys (like ObjectId) into randomly distributed hash values, eliminating write hot spots. The trade-off is that range queries on the field become scatter-gather, since hash values are not stored in original order.

// Hashed sharding: uniform write distribution
sh.shardCollection('mydb.events', { _id: 'hashed' })

// Range query on _id is now scatter-gather (con)
// But all inserts are evenly distributed (pro)

Zone Sharding for Geographical Distribution

MongoDB allows zone sharding where you assign shard key ranges to specific shards using tags (zones). This is useful for data residency requirements: European user data can be pinned to EU-region shards, US data to US shards. Zone sharding requires a compound shard key with a region prefix as the first component.

// Tag shards with zones
sh.addShardTag('shard01', 'EU')
sh.addShardTag('shard02', 'US')

// Assign key ranges to zones
sh.addTagRange('mydb.users',
  { region: 'EU', userId: MinKey },
  { region: 'EU', userId: MaxKey },
  'EU'
)

Evaluating Candidates: A Practical Checklist

When evaluating shard key candidates: 1) Run a cardinality check — db.col.distinct('field').length should be in the thousands or more. 2) Check frequency distribution with an aggregation. 3) Determine if the field is monotonic (timestamps, auto-increment). 4) Review your top 5 most frequent queries — does the candidate field appear in their filter?

// Quick cardinality check
db.events.distinct('userId').length   // want > 10,000+

// Frequency check — any value > 1% of docs is a risk
const total = db.events.countDocuments()
db.events.aggregate([
  { $group: { _id: '$userId', n: { $sum: 1 } } },
  { $match: { n: { $gt: total * 0.01 } } }
])

The _id Field as a Hashed Shard Key

A common and safe default for many workloads is to use { _id: 'hashed' }. MongoDB ObjectId values, while monotonic, become evenly distributed after hashing. This gives uniform write distribution out of the box. The main limitation is that any range query on _id becomes scatter-gather — but for most document-level lookup workloads this is acceptable.

// Safe default for write-heavy workloads without range queries
sh.shardCollection('mydb.messages', { _id: 'hashed' })

// Single-document lookup by _id is still targeted
// (hash is deterministic: mongos knows which shard)
db.messages.findOne({ _id: ObjectId('...') })

Shard Key Selection in Atlas

MongoDB Atlas provides a Shard Key Advisor in the Performance Advisor that analyzes your query patterns and recommends shard keys based on actual usage. It can detect monotonic keys, frequency skew, and missing indexes. Using the advisor before sharding is especially helpful for production workloads where query patterns are already established.

Quick Check

Test your understanding of MongoDB & NoSQL Databases concepts from this lesson.

Lesson Recap

In this lesson you learned: a good shard key has high cardinality, low frequency skew, and avoids monotonic values, compound shard keys combine coverage for distribution and query targeting, and hashed sharding neutralizes monotonic key hot spots at the cost of range query efficiency. Next up we compare ranged vs hashed sharding strategies in detail.

เริ่มต้นได้ฟรี

เรียนรู้ 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 ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การเลือกคีย์ชาร์ด: ความหลากหลาย ความถี่ ความเป็นโมโนโทน” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน MongoDB Academy นี้ได้ไหม

ได้ บทเรียน MongoDB Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. แนวคิดการแบ่งส่วน: ชังก์ ตัวปรับสมดุล และคีย์ชาร์ด
  2. การเลือกคีย์ชาร์ด: ความหลากหลาย ความถี่ ความเป็นโมโนโทน
  3. กลยุทธ์การแบ่งส่วนแบบช่วงเทียบกับแบบแฮช
  4. การแบ่งส่วนตามโซน: การตรึงข้อมูลไว้ในภูมิภาค
← กลับไปที่ MongoDB Academy