Shard Keys
Shard Keys: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 66 of 100
Shard Keys
Foundations & CRUD ✓ → Queries & Schema ✓ → Aggregation & Scale → Atlas & Projects
Aggregation & Scale · 3 — Pipelines · ~10 min · MongoDB — Replication & Sharding
What is this?
The shard key is the field(s) MongoDB uses to partition documents into chunks. Good keys have high cardinality, even distribution, and appear in most queries. Ranged and hashed keys behave differently.
Why should you care?
A bad key (monotonically increasing _id only) puts all inserts on one hot shard. A good key spreads writes.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
// Ranged compound key for time-series style access
sh.shardCollection("NoSQLVerse.readings", { deviceId: "hashed" })
// Or ranged:
// sh.shardCollection("NoSQLVerse.orders", { tenantId: 1, orderId: 1 })
db.readings.find({ deviceId: "sensor-42", ts: { $gte: ISODate("2026-07-19") } })
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- Hashed deviceId spreads devices across shards.
- Queries that include deviceId target specific shards.
- orders often use tenantId first so each tenant’s data tends to colocate for targeted queries.
Practice next
- List your top queries and which fields they always include.
- Reject keys with <1000 distinct values for large collections.
- Prefer compound keys that match query patterns.
- Sketch a key for multi-tenant orders.
- Explain why status alone is a terrible shard key.
Remember
Shard key partitions documents. Need cardinality + query affinity. Hashed keys spread writes evenly.
IoT deviceId hashing
Millions of sensors write continuously; hashed deviceId avoids a single hot shard.
Outcome: Ingest throughput scales near-linearly with shard count.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!