Agentic hosting is here. Connect to our MCP now ->

Blog

A comprehensive guide to understanding MongoDB sharding

The shard key is the most important decision you'll make when you shard a collection, because it decides where every document lives.

·by Jeremy Holcombe

As your data and traffic grow, a single database server eventually reaches its limits. You can move to a bigger server for a while, but at some point, there's no bigger server to move to, or it costs far more than it's worth. That's when you need to spread your data across several servers, with a technique called database sharding.

In this guide, we'll explain how sharding works in MongoDB, the components of a sharded cluster, how to set one up step by step, and the best practices and common mistakes to keep in mind. All the commands were tested on a sharded cluster running MongoDB 9.0.

What is database sharding?

Database sharding is a technique that splits a database horizontally into smaller parts, called shards, and stores each shard on a different server. Each shard holds a subset of the data, and together, the shards hold the whole dataset.

Sharding is a form of horizontal scaling, or scaling out: instead of upgrading a single server, you add more servers. This lets a database grow beyond the storage, memory, and processing power of any one machine.

Sharding also adds complexity. Your data now lives on several servers, queries may need to reach more than one of them, and you have more servers to run and monitor. That's why you should consider sharding when you actually need it, and not before. Before you shard, make sure you've optimized your queries and indexes, and that scaling up to a larger server is no longer practical.

Many databases support sharding, either natively or through extensions. MongoDB has built-in sharding, which is one of the reasons it's popular for applications with very large datasets.

What is sharding in MongoDB?

A MongoDB database contains collections, and each collection contains documents. When you shard a collection, MongoDB distributes its documents across several shards, based on a field or fields that you choose, called the shard key.

Your application doesn't need to know where each document is. It connects to a router, called mongos, which sends each query to the shards that hold the relevant data, and combines the results. To your application, a sharded cluster looks like a single database.

Large organizations use sharding to handle huge workloads. For example, according to MongoDB, Telefónica Tech uses a sharded MongoDB deployment to manage data from millions of IoT devices around the world.

Benefits of MongoDB sharding

Here are the main benefits of sharding a MongoDB database.

Storage capacity

Each shard holds only part of the data, so you can increase the total storage of the cluster by adding shards as your data grows.

Read and write throughput

MongoDB distributes reads and writes across the shards, so each shard handles only part of the workload. To handle more traffic, you add more shards.

High availability

In production, each shard and the config servers run as replica sets, with several copies of the data. If a server fails, its replica set elects a new primary, and the cluster keeps working. Even if a whole shard becomes unavailable, the cluster can still serve reads and writes for the data on the other shards.

A smaller blast radius

When an unsharded database goes down, every user is affected. In a sharded cluster, a problem with one shard affects only the data on that shard.

Geo-distribution

With zone sharding, you can keep specific data on shards in specific regions. For example, you can store European customers' data on shards in Europe, to give them lower latency or to meet data residency rules.

Components of a MongoDB sharded cluster

A sharded cluster has three types of components: shards, config servers, and query routers.

1. Shards

Each shard holds a subset of the sharded data. Shards must be deployed as replica sets, which provides high availability and redundancy.

Each database in a sharded cluster also has a primary shard, which holds the database's unsharded collections. The primary shard isn't related to the primary member of a replica set. You can change a database's primary shard with the movePrimary command, but moving it can take a long time if there's a lot of unsharded data.

To see an overview of the cluster, including each database's primary shard and how the data is distributed, run sh.status() in mongosh.

2. Config servers

Config servers store the cluster's metadata, such as which shards exist and which ranges of data each shard holds. They must run as a replica set, and you can find their data in the config database.

The config server replica set has a few restrictions:

  • It can't have arbiters, members that vote in elections but don't hold data.
  • It can't have delayed members, which apply changes with a delay.
  • All its members must build indexes.

If the config server replica set loses its primary and can't elect a new one, the cluster's metadata becomes read-only. You can still read and write data on the shards, but MongoDB can't move data between shards until a new primary is elected.

Since MongoDB 8.0, a config server can also store application data, as a config shard. This reduces the number of servers you need for a small cluster.

3. Query routers (mongos)

The mongos process is the query router. Your application connects to mongos, as it would connect to a single MongoDB server, and mongos uses the metadata from the config servers to route each operation:

  • If a query includes the shard key, mongos can send it only to the shards that hold the matching data. This is called a targeted query.
  • If a query doesn't include the shard key, mongos sends it to every shard, and merges the results. This is called a broadcast or scatter-gather query, and it gets slower as you add shards.

For operations like sorting, each shard sorts its own results, and mongos merges them.

For a production cluster, MongoDB recommends:

  • Each shard as a 3-member replica set.
  • The config servers as a 3-member replica set.
  • One or more mongos routers, often one on each application server.

For development and testing, a cluster with single-member replica sets for the shards and config servers, and one mongos, is enough. That's the setup we use in the next section.

How does MongoDB sharding work?

When you shard a collection, MongoDB splits its documents into ranges of shard key values, called chunks, and assigns the chunks to shards. A background process, the balancer, moves data between shards to keep the amount of data on each shard even. When you add a shard, the balancer gradually moves data to it.

MongoDB supports two main sharding strategies:

  • Ranged sharding divides the data into ranges of shard key values. Documents with close shard key values are stored together, which makes range queries efficient, because they can target a single shard.
  • Hashed sharding computes a hash of the shard key value, and distributes documents by the hash. This spreads writes evenly across the shards, even when the shard key value always increases, but range queries on the shard key have to go to every shard.

Your application doesn't need to change to use sharding. It connects to mongos, and the cluster handles the rest.

How to set up MongoDB sharding step by step

To set up a sharded cluster, you'll start the config servers and shards as replica sets, start the mongos router, add the shards to the cluster, and shard a collection.

This example uses three hosts: cfg1.example.net for the config server, shard1.example.net and shard2.example.net for two shards, and mongos.example.net for the router. Each replica set has a single member, which is fine for testing. In production, use three members per replica set, and enable access control and TLS between the members.

1. Start the config server replica set

On the config server, create a data directory and start mongod as a config server:

mkdir -p /data/configdb
mongod --configsvr --replSet configRS --dbpath /data/configdb --port 27019 --bind_ip localhost,cfg1.example.net

The --configsvr flag makes this server a config server, and --replSet sets the name of its replica set. --bind_ip makes mongod listen on the server's hostname, so the other members of the cluster can connect.

Then connect to it with mongosh and initiate the replica set:

mongosh --port 27019
rs.initiate({
  _id: "configRS",
  configsvr: true,
  members: [{ _id: 0, host: "cfg1.example.net:27019" }]
})

2. Start the shard replica sets

On each shard server, start mongod with the --shardsvr flag and its own replica set name. On the first shard server:

mkdir -p /data/shard1
mongod --shardsvr --replSet shard1RS --dbpath /data/shard1 --port 27018 --bind_ip localhost,shard1.example.net

Connect with mongosh --port 27018 and initiate the replica set:

rs.initiate({
  _id: "shard1RS",
  members: [{ _id: 0, host: "shard1.example.net:27018" }]
})

Repeat these steps on the second shard server, with shard2RS and shard2.example.net.

3. Start the mongos router

On the router's host, start mongos and point it to the config server replica set, in the format <replica set name>/<host>:<port>:

mongos --configdb configRS/cfg1.example.net:27019 --port 27017 --bind_ip localhost,mongos.example.net

4. Connect to mongos

Connect to the router with mongosh:

mongosh --host mongos.example.net --port 27017

The prompt shows [direct: mongos], which confirms you're connected to the router. From now on, your applications connect to mongos too, never directly to the shards.

5. Add the shards to the cluster

Add each shard with sh.addShard(), using its replica set name and a member's address:

sh.addShard("shard1RS/shard1.example.net:27018")
sh.addShard("shard2RS/shard2.example.net:27018")

Each command returns shardAdded with the shard's name, and ok: 1.

6. Shard a collection

Finally, shard a collection with sh.shardCollection(), passing the collection's full name and the shard key. This shards the orders collection of the shop database with a hashed shard key on customerId:

sh.shardCollection("shop.orders", { customerId: "hashed" })

MongoDB creates the database, the collection, and an index on the shard key if they don't exist. You don't need to run sh.enableSharding() first: since MongoDB 6.0, it's optional.

7. Check the data distribution

Insert some data through mongos, then check how it's distributed across the shards:

use shop
db.orders.getShardDistribution()

In our test, after inserting 10,000 orders, the hashed shard key spread them almost evenly:

Shard shard2RS at shard2RS/shard2:27018
{
  data: '331KiB',
  docs: 4992,
  chunks: 1,
  ...
}
---
Shard shard1RS at shard1RS/shard1:27018
{
  data: '332KiB',
  docs: 5008,
  chunks: 1,
  ...
}

You can also check how a query is routed with explain(). A query on the shard key, such as db.orders.find({ customerId: 42 }), shows the SINGLE_SHARD stage, because mongos sends it to one shard. A query on another field, such as db.orders.find({ total: 5 }), shows SHARD_MERGE, because mongos sends it to every shard and merges the results.

Your sharded cluster is now ready to scale horizontally. To add capacity later, start another shard replica set and add it with sh.addShard(), and the balancer moves data to it.

Best practices for MongoDB sharding

Once your cluster is running, these practices keep it fast and reliable.

1. Choose the right shard key

The shard key is the most important decision you'll make when you shard a collection, because it decides where every document lives. A good shard key:

  • Has high cardinality, meaning many distinct values, so the data can be split into many chunks.
  • Distributes writes evenly, so no single shard becomes a hotspot.
  • Matches your most common queries, so they can be targeted to a single shard instead of every shard.

Analyze your data and your queries before you choose. MongoDB's analyzeShardKey command can help you compare candidate shard keys.

2. Choose between hashed and ranged sharding

Use ranged sharding when your application often queries ranges of shard key values, such as orders between two dates for a customer, because those queries can target a single shard.

Use hashed sharding when you need writes spread evenly, especially when the shard key value always increases, like a timestamp or an ObjectId. Hashed sharding makes range queries on the shard key go to every shard, though.

3. Plan for growth

Add shards before your existing shards are overloaded. Moving data to a new shard adds load to the cluster, so it's best to do it while you have spare capacity, ideally during low-traffic periods.

4. Use replica sets with separate servers

In production, run each shard and the config servers as 3-member replica sets, with each member on a separate server, and ideally in separate availability zones. That way, the cluster survives the failure of any single server.

5. Monitor the cluster

Monitor the CPU, memory, disk, and network usage of every shard, the config servers, and the routers, along with the balancer's activity and how evenly data is distributed. You can use MongoDB's mongostat and mongotop, MongoDB Atlas's monitoring if you use Atlas, or tools like Prometheus and Datadog.

6. Back up and test your restores

Back up all the shards and the config servers consistently, so you can restore the whole cluster to the same point in time. Test your restores regularly, because a backup you can't restore doesn't protect you.

Common mistakes to avoid when sharding MongoDB

These are some of the most common mistakes teams make with sharding.

1. Choosing a shard key that always increases with ranged sharding

A common mistake is to use ranged sharding with a shard key whose value always increases, such as a timestamp or an ObjectId, which starts with a timestamp. All new documents have the highest values, so they all go to the same chunk, on the same shard. That shard handles every insert, and adding more shards doesn't increase your write capacity.

If you need to shard on a field like this, use hashed sharding on it, or a compound shard key that starts with a field with many distinct values.

2. Assuming you can't fix the shard key

In older versions of MongoDB, shard keys were permanent. That's no longer true:

  • Since MongoDB 4.2, you can update a document's shard key value, unless the shard key is the _id field.

  • Since MongoDB 4.4, you can refine a shard key by adding fields to the end of it, with refineCollectionShardKey.

  • Since MongoDB 5.0, you can change a collection's shard key completely by resharding it:

    sh.reshardCollection("shop.orders", { total: 1 })

Resharding copies the whole collection to a new distribution in the background, so it takes time and resources. In our test, resharding 10,000 documents to a ranged key on total took about 100 seconds, because MongoDB keeps a resharding operation running for a minimum duration by default. Plan resharding for large collections carefully, but know it's an option if your shard key turns out to be a poor fit.

3. Running queries that don't include the shard key

Queries without the shard key go to every shard, so they get slower as the cluster grows. Design your shard key around your most frequent queries, and check with explain() whether important queries are targeted to a single shard.

4. Failing to monitor the cluster

Sharding adds more moving parts, so problems are harder to spot. Set up monitoring and alerts for resource usage, slow queries, replication lag, and data distribution across shards.

5. Waiting too long to add a shard

When shards are already overloaded, adding a new shard makes things worse at first, because the balancer has to move data to it while the cluster is busy. Add capacity proactively, and schedule data migrations for quieter times with the balancer window.

6. Under-provisioning the config servers

Every operation that needs to know where data lives depends on the config servers. If they don't have enough CPU, memory, or disk, the whole cluster slows down. Give the config servers dedicated resources, or, for small clusters, consider a config shard.

7. Skipping backups and tests

Back up the cluster, test your restores, and load-test the cluster with realistic data and queries before you go to production.

MongoDB sharding vs clustered collections

MongoDB also has clustered collections, created with a clustered index on the _id field. They're often mentioned alongside sharding, but they solve different problems.

Sharding is horizontal scaling: it spreads a collection's data across several servers, so you can store more data and handle more traffic than one server can.

A clustered collection stores its documents in the order of its clustered index key, on a single server. This makes queries and inserts on that key more efficient, especially for time-ordered data, but it doesn't add capacity.

If your application needs more storage or throughput than one server can provide, sharding is the answer. If you want faster queries on _id ranges in a collection that fits on one server, a clustered collection may help. You can also use both.

Summary

A sharded cluster splits your data across several servers so your database can grow beyond the limits of a single machine. It consists of shards, config servers, and mongos routers, and it distributes data by a shard key, which you should choose carefully to spread data evenly and target your most common queries.

With sharding, your application can scale out, stay available when servers fail, and keep data close to your users.

If you're still choosing a database, see our comparison of MongoDB vs PostgreSQL, and our guide to creating a MongoDB database. And when your app is ready, you can deploy it on Sevalla's Application Hosting.

Deep dive into the cloud!

Deploy your application, database, or static site in minutes.