Shard Keys in MongoDB (original) (raw)

Last Updated : 5 May, 2026

Shard keys are central to MongoDB sharding, as they control how data is split and distributed across shards to improve scalability and performance in a sharded cluster.

Importance of Shard Keys

Here are some important points of Shard Keys:

Shard Key Specification

The specification of a shard key is one of the most important decisions when designing a MongoDB sharded cluster. It involves choosing one or more fields that will determine how the data is partitioned.

Changing a Document’s Shard Key Value

In some cases, updating a document’s shard key value requires adhering to MongoDB’s constraints and procedures to preserve data integrity, consistency, and correct chunk placement across the cluster.

1. Shard Key Indexes

2. Choosing a Shard Key

3. Shard Key Cardinality

The diagram shows a sharded cluster using field X as the shard key. When X has low cardinality, most inserts go to the same shard range, causing uneven data distribution (hotspots).

shard1

Shard Key Cardinality

4. Shard Key Frequency

The diagram shows that high-frequency shard key values for field X cause insert operations to concentrate on specific shards, creating hotspots.

shard2

Shard Key Frequency

Implementing Shard Keys

Let's consider an example to illustrate the concept of shard keys in MongoDB:

Step 1: Create a Collection and Define a Shard Key

db.createCollection("users");
db.users.createIndex({ "username": 1 });

Step 2: Enable Sharding on the Database

sh.enableSharding("testDB");

Step 3: Shard the Collection

sh.shardCollection("testDB.users", { "username": 1 });

Step 4: Insert Data

db.users.insertOne({ username: "user1", email: "user1@example.com" });
db.users.insertOne({ username: "user2", email: "user2@example.com" });

Step 5: Query Data

db.users.find({ username: "user1" });