Hashed indexes are specialized for equality queries and hash-based sharding, while B-Tree indexes are the general-purpose choice for supporting range queries, sorting, and equality lookups.
Choosing between a hashed index and a standard B-Tree index in MongoDB depends entirely on your query patterns and data distribution requirements. Standard B-Tree indexes are the default and most versatile type, optimized for a wide range of operations including equality matches, range queries, and sorting. Hashed indexes, on the other hand, are a specialized tool designed primarily for two scenarios: supporting hash-based sharding and performing equality lookups on fields that are typically large or have poor B-Tree selectivity.
Use B-Tree for range queries ($gt, $lt) and sorting - B-Tree indexes maintain order, hashed indexes do not
Use B-Tree for compound indexes with multiple query patterns - Hashed indexes support only one hashed field per compound index
Use B-Tree when you need unique constraints - Hashed indexes cannot be created with the unique option
Use B-Tree for fields containing arrays - Hashed indexes cannot be created on array fields
Use Hashed for hash-based sharding with monotonically increasing keys - Prevents write hotspots in sharded clusters
Use Hashed for equality-only queries on large string fields - Can be more memory-efficient than B-Tree