Hashed Index in MongoDB: What It Is and When to Use
hashed index in MongoDB is a special type of index that stores a hash of the indexed field's value instead of the value itself. It helps distribute data evenly across a sharded cluster and speeds up equality queries on the indexed field.How It Works
Imagine you have a big box of mail and you want to quickly find a letter by its address. Instead of looking through every letter, you use a system that turns the address into a unique code (a hash). This code points you directly to the letter's location. In MongoDB, a hashed index works similarly by converting the value of a field into a hash value and indexing that hash.
This means when you search for a specific value, MongoDB hashes your search term and looks up the hash in the index, which is very fast. The hashing also spreads the data evenly, which is especially useful when MongoDB splits data across multiple servers (sharding) to balance the load.
Example
user_id field and shows how to query using it.use mydatabase;
db.users.createIndex({ user_id: "hashed" });
db.users.insertMany([
{ user_id: 101, name: "Alice" },
{ user_id: 102, name: "Bob" },
{ user_id: 103, name: "Charlie" }
]);
db.users.find({ user_id: 102 });When to Use
Use a hashed index when you want to speed up queries that check for exact matches on a field, especially in large collections. It is ideal for sharded clusters because it helps distribute data evenly across servers, preventing hotspots where one server gets too much traffic.
For example, if you have a user database and you often look up users by their unique ID, a hashed index on the user ID field will make those lookups fast and keep your system balanced.
Key Points
- A hashed index stores a hash of the field's value, not the value itself.
- It speeds up equality queries (exact matches) on the indexed field.
- It helps distribute data evenly in sharded MongoDB clusters.
- It is not suitable for range queries (like greater than or less than).