17 / 18

When would you use a Hashed Index vs. a standard B-Tree index?

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.

Creating Different Index Types
Decision Matrix: When to Use Each
  1. 1

    Use B-Tree for range queries ($gt, $lt) and sorting - B-Tree indexes maintain order, hashed indexes do not

  2. 2

    Use B-Tree for compound indexes with multiple query patterns - Hashed indexes support only one hashed field per compound index

  3. 3

    Use B-Tree when you need unique constraints - Hashed indexes cannot be created with the unique option

  4. 4

    Use B-Tree for fields containing arrays - Hashed indexes cannot be created on array fields

  5. 5

    Use Hashed for hash-based sharding with monotonically increasing keys - Prevents write hotspots in sharded clusters

  6. 6

    Use Hashed for equality-only queries on large string fields - Can be more memory-efficient than B-Tree