Understand hashed equality access and shard-key distribution tradeoffs without confusing a standalone hashed index with a real sharded-cluster distribution test.

Hashed Indexes and Their Role in Shard-Key Distribution

Batch heterogeneous writes safely, interpret partial success, compare ordered and unordered execution, and use modern cross-namespace bulk APIs without assuming all-or-nothing behavior.

Intermediate100–140 minutesHashed equality + hash-observation labMongoDB 8.3.8 · mongosh 2.10.0Last reviewed: September 2026

Learning objectives

01

Explain that a hashed index stores a deterministic hash of the field value rather than preserving the field’s natural order.

02

Use hashed indexes for equality lookup and understand why ordinary range predicates cannot use hashed ordering.

03

Use convertShardKeyToHashed() to make the transformation observable on Community Server.

04

Separate “this standalone has a hashed index” from the stronger claim “data is distributed across shards.”

05

Choose hashed shard keys from routing, cardinality, monotonic-write, and range-query requirements.

Reproducible lab baseline

This lesson pins MongoDB Community Server 8.3.8 with mongodb/mongodb-community-server:8.3.8-ubuntu2204-slim and mongosh 2.10.0. The server is a disposable standalone published only on loopback 127.0.0.1:27070. Authentication and TLS are disabled only for this isolated lab. Feature Compatibility Version (FCV) is observed but never changed. Default read/write concern and primary read preference apply. Atlas, KMS, and Enterprise Advanced are not mandatory. The mandatory lab is standalone, so it can demonstrate hashed index semantics and computed hash values but cannot demonstrate real chunk placement, balancer behavior, or multi-shard routing. Those require a sharded cluster and are taught in Chapters 16–17. Runtime output shown as “expected” is documentation-derived because this generation environment has no Docker/mongod/mongosh runtime.

Evidence before index enthusiasm

Specialized indexes are useful only when their eligibility rules match the workload. Every lab therefore inspects index metadata, matching and non-matching query shapes, explain evidence, and state transitions. Tiny fixtures prove semantics—not production latency, cache behavior, or sharded-cluster distribution.

1. Hashing trades order for distribution

A hashed index stores the hash of a field value. Equal input values map to the same hash, so equality lookup can use the index. Natural range relationships are intentionally lost: lexically adjacent event IDs do not remain adjacent in hashed key space. That is why hashed sharding can spread monotonically increasing keys across shard-key ranges, but range predicates on the hashed field cannot use the hashed index as an ordered range access path.

Need Hashed behavior Design consequence
Exact event ID Same value → same hash Good equality routing/access candidate.
Event-ID range Natural ordering not preserved Use a ranged/ordinary index for range access.
Distribute monotonic IDs Hashes scatter values across key space Useful sharding strategy when routing tradeoff is acceptable.
Tenant-scoped routing Depends on shard-key design Consider compound hashed keys and actual query shapes; do not hash blindly.

2. Build a hashed index and inspect actual hash values

bash · isolated Chapter 11 Lesson 4 lab setup
docker rm -f atlasmart-mongo-ch11-l4 2>/dev/null || truedocker volume rm atlasmart-mongo-ch11-l4-data 2>/dev/null || truedocker run -d --name atlasmart-mongo-ch11-l4 \  -p 127.0.0.1:27070:27017 \  -v atlasmart-mongo-ch11-l4-data:/data/db \  mongodb/mongodb-community-server:8.3.8-ubuntu2204-slimmongosh "mongodb://127.0.0.1:27070/atlasmart?directConnection=true" --quiet --eval \'printjson({server:db.version(),hello:db.hello().isWritablePrimary}); printjson(db.getSiblingDB("admin").runCommand({getParameter:1,featureCompatibilityVersion:1}))' 
javascript · seed monotonically named events
const c=db.events_ch11_l4;c.drop();const docs=[];for(let i=1;i<=40;i++){ docs.push({_id:i,eventId:`evt-${String(i).padStart(3,"0")}`,tenantId:`tenant-${(i%5)+1}`,createdAt:new Date(1760000000000+i*60000),payload:`p-${i}`});}c.insertMany(docs);printjson(c.find({},{_id:0,eventId:1,tenantId:1,createdAt:1}).limit(8).toArray());
javascript · create hashed index and calculate hashes
const c=db.events_ch11_l4;print(c.createIndex({eventId:"hashed"},{name:"idx_eventId_hashed"}));printjson(c.getIndexes());for(const v of ["evt-001","evt-002","evt-010","evt-020","evt-040"]){ printjson({value:v,hash:convertShardKeyToHashed(v)});}

3. Equality can use hashed access

javascript · explain exact lookup through hashed index
const c=db.events_ch11_l4;const filter={eventId:"evt-020"};printjson(c.find(filter,{_id:0,eventId:1,tenantId:1}).hint("idx_eventId_hashed").explain("executionStats"));printjson(c.find(filter,{_id:0,eventId:1,tenantId:1}).hint("idx_eventId_hashed").toArray());

4. Deliberately wrong: expect a hashed range scan

The query “evt-010 through evt-019” is about natural string order. A hash is not monotonic with that string order. If range access is important, keep an ordinary ordered index or choose range-based shard-key design.

javascript · range query and forced-hash diagnostic
const c=db.events_ch11_l4;const filter={eventId:{$gte:"evt-010",$lt:"evt-020"}};printjson(c.find(filter,{_id:0,eventId:1}).explain("executionStats"));try{ printjson(c.find(filter,{_id:0,eventId:1}).hint("idx_eventId_hashed").explain("executionStats"));}catch(e){ printjson({name:e.name,code:e.code,message:e.message}); }

5. Hash values are not a standalone sharding simulation

convertShardKeyToHashed() uses the same hash function and lets us see that nearby input values do not produce nearby ordered values. But printing hashes on one process does not prove distribution across shards. Real distribution depends on sharded-cluster metadata, chunks/ranges, balancer activity, zones, and the shard key.

javascript · observe many computed hashes without claiming shard placement
const values=[];for(let i=1;i<=200;i++) values.push(`evt-${i}`);const hashes=values.map(v=>({v,h:NumberLong(convertShardKeyToHashed(v))}));const ordered=hashes.slice().sort((a,b)=>a.h.toString().localeCompare(b.h.toString()));printjson({sample:hashes.slice(0,10),note:"Hashes are not in eventId lexical order; a sharded cluster uses hashed shard-key ranges, not this standalone array, to distribute chunks."});
Shard-key prerequisite

For a collection that already contains data, a supporting index is required before sharding. An empty collection can have the shard-key index created as part of sharding. The actual sharded-cluster workflow is deferred to the sharding chapters.

6. Verification, cleanup, and production judgment

Verification checklist

  • The index metadata uses "hashed" on eventId.
  • convertShardKeyToHashed() returns deterministic 64-bit hash values.
  • An equality lookup is explained against the hashed candidate.
  • The range query is not described as a hashed range scan.
  • No claim of multi-shard distribution is made from a standalone lab.
  • The lesson distinguishes hashed index semantics from hashed sharding deployment.

Production judgment. Hashed shard keys can smooth writes for monotonic keys, but they weaken range locality and can make range-based operations scatter across shards. Choose high-cardinality fields, inspect common routing predicates, and test distribution under real sharded topology. A compound hashed index can contain one hashed term plus ordered terms, but added fields do not erase routing tradeoffs. Security and tenant isolation still require authorization; a hashed tenant key is not an access-control boundary. Lesson 5 closes the chapter by separating built-in self-managed text/geospatial indexes from the richer Search/Vector Search subsystem.

bash · cleanup / full reset
docker rm -f atlasmart-mongo-ch11-l4docker volume rm atlasmart-mongo-ch11-l4-data

Check your understanding

  1. What does a hashed index store?
  2. Can a range query on the hashed field use natural hash ordering?
  3. Why is a monotonically increasing key often considered for hashed sharding?
  4. Does creating a hashed index on a standalone distribute data across shards?
  5. What does convertShardKeyToHashed() prove?
Review the answers

1. A deterministic hash of the indexed field value.

2. No. Hashing destroys the natural ordering needed for ordinary range access.

3. The hash can spread sequential input values across hashed key space rather than concentrating new writes at one ranged-key edge.

4. No. Distribution requires a sharded cluster and shard-key metadata.

5. It shows the exact hash transformation used for hashed shard keys/indexes; it does not prove chunk placement or balancer behavior.

Authoritative references

Keep knowledge open

Help the academy stay free and grow.

If these tutorials save you time, a small donation supports new lessons, technical review, diagrams, examples, and long-term maintenance.

ETHEthereum / ERC-20 only
0x716c4Ab160C4B66F31a28AE2448BfF68fc3a2ef0

Send only Ethereum or ERC-20 compatible assets to this address.