# How to Enable Sharding and Configure Sharding Keys in MongoDB Docker Clusters

> Easily enable sharding and configure sharding keys in MongoDB Docker clusters. Learn the commands to shard collections effectively and optimize your database.

- Repository: [Jin/mongodb-cluster-docker-compose](https://github.com/minhhungit/mongodb-cluster-docker-compose)
- Tags: how-to-guide
- Published: 2026-03-07

---

**Enable sharding by connecting to a `mongos` router, running `sh.enableSharding("databaseName")`, and then issuing `db.adminCommand({ shardCollection: "db.collection", key: { field: "hashed" } })` to define the shard key.**

The `minhhungit/mongodb-cluster-docker-compose` repository provides a production-ready Docker Compose template for deploying a MongoDB sharded cluster. Once the cluster is running, you must explicitly enable sharding and configure sharding keys to distribute data across the replica sets. This guide walks through the exact commands and configuration patterns used in the repository.

## Understanding the Sharded Cluster Architecture

Before you enable sharding, it is essential to understand how the components interact. The repository defines three distinct layers in [`docker-compose.yml`](https://github.com/minhhungit/mongodb-cluster-docker-compose/blob/main/docker-compose.yml):

### Config Servers

The config servers store the cluster's metadata, including the mapping of chunks to shards. The repository deploys a three-node replica set (`configsvr01`, `configsvr02`, `configsvr03`) that must be online before any sharding commands are issued.

### Shard Replica Sets

Data lives in shards. The repository provides three independent replica sets (`rs-shard-01`, `rs-shard-02`, `rs-shard-03`), each containing three data-bearing nodes. When you enable sharding, MongoDB distributes chunks of your collections across these replica sets.

### MongoS Routers

Client applications never connect directly to shards. Instead, they connect to `mongos` instances (`router01`, `router02` in the repository). These routers cache the cluster metadata from the config servers and route read/write operations to the correct shard based on the sharding key you configure.

## Prerequisites for Enabling Sharding

You cannot configure sharding keys until the cluster is fully initialized. The repository automates this through entrypoint scripts.

Start the cluster:

```bash
docker-compose up -d

```

The [`scripts/init-router.js`](https://github.com/minhhungit/mongodb-cluster-docker-compose/blob/main/scripts/init-router.js) file automatically executes against the routers once the config servers and shards are ready. This script registers each shard replica set with the cluster using `sh.addShard()`, making them available for data distribution. Wait approximately 30-60 seconds after startup for all replica sets to elect primaries and for the initialization scripts to complete.

## How to Enable Sharding and Configure Sharding Keys

Once the cluster is ready, you enable sharding at the database level and then configure the shard key for individual collections.

### Step 1: Connect to the Router

Access the `mongos` container to run sharding commands:

```bash
docker-compose exec router01 mongosh --port 27017

```

You must run all subsequent commands inside this shell.

### Step 2: Enable Sharding for the Database

Before a collection can be sharded, its parent database must be marked as partitioned:

```javascript
sh.enableSharding("MyDatabase")

```

This command updates the config servers to track that `MyDatabase` supports sharded collections.

### Step 3: Configure the Sharding Key

Define how MongoDB distributes documents across shards by issuing an `adminCommand`. The repository documentation demonstrates a compound shard key combining hashed and ranged fields:

```javascript
db.adminCommand({
  shardCollection: "MyDatabase.MyCollection",
  key: { oemNumber: "hashed", zipCode: 1, supplierId: 1 },
  numInitialChunks: 3
})

```

**Key components explained:**

- **`oemNumber: "hashed"`** – Distributes writes evenly across all shards by hashing the value, preventing "hot" shards from sequential inserts.
- **`zipCode: 1`** and **`supplierId: 1`** – Enable targeted queries and range operations on these fields.
- **`numInitialChunks: 3`** – Pre-splits the collection into three chunks, one for each shard in the repository's default configuration, ensuring immediate distribution.

## Choosing an Effective Sharding Strategy

The shard key you configure determines performance and scalability. Follow these principles when defining your key:

- **Distribute writes evenly** – Use a hashed prefix (`{ field: "hashed" }`) to avoid write hotspots on a single shard.
- **Support query isolation** – Include fields frequently used in equality matches or range queries as suffixes in compound keys.
- **Avoid monotonic values** – Do not use timestamps or auto-incrementing IDs as the first field in a ranged key unless hashed.

For read-heavy workloads with geographic data, a compound key like `{ countryCode: 1, userId: "hashed" }` routes country-specific queries to specific chunks while distributing user data evenly.

## Verifying Your Sharding Configuration

After enabling sharding and configuring keys, confirm the cluster is distributing data correctly.

Check the overall cluster status:

```bash
docker-compose exec router01 mongosh --port 27017 --eval "sh.status()"

```

Verify chunk distribution for a specific collection:

```bash
docker-compose exec router01 mongosh --port 27017 --eval "db.MyCollection.getShardDistribution()"

```

The `getShardDistribution()` output shows document counts and data sizes per shard, confirming that MongoDB is balancing chunks according to your configured sharding key.

## Summary

- The `minhhungit/mongodb-cluster-docker-compose` repository provides a complete sharded cluster with config servers, three shard replica sets, and `mongos` routers.
- Enable sharding by connecting to a router container and running `sh.enableSharding("databaseName")`.
- Configure sharding keys using `db.adminCommand({ shardCollection: "db.collection", key: { ... } })`, choosing between hashed and ranged fields based on your write and query patterns.
- Verify distribution with `sh.status()` and `db.collection.getShardDistribution()`.

## Frequently Asked Questions

### What is the difference between a config server and a shard?

Config servers store metadata about the cluster topology, including which databases are sharded and how chunks map to shards. Shards are replica sets that store the actual application data. Routers query config servers to determine where to route read and write operations.

### Can I change the shard key after enabling sharding?

No, MongoDB does not support changing the shard key for an existing sharded collection. You must drop the collection and recreate it with a new shard key, or migrate data to a new collection with the desired key. Plan your sharding strategy carefully before executing `shardCollection`.

### How do I add more shards to an existing cluster?

Add new shard replica sets to the [`docker-compose.yml`](https://github.com/minhhungit/mongodb-cluster-docker-compose/blob/main/docker-compose.yml) file, then run `docker-compose up -d` to start the new containers. Connect to a router and run `sh.addShard("rs-shard-04/hostname:port")` for each new shard. MongoDB will automatically begin balancing chunks to the new shards.

### What happens if the config servers go down?

If all three config servers become unavailable, the cluster cannot process metadata changes such as chunk migrations or schema updates. However, existing `mongos` instances maintain a cached copy of the routing table and can continue routing queries to shards for a limited time. Always maintain the config server replica set with a majority of nodes online.