Skip to content
MongoDB

Sharding

Distribute data across shards by a shard key.

By EZ4Code Team
shardingscalingcluster

Code

// Enable sharding on a database
sh.enableSharding("shop")

// Create an index on the shard key (required)
db.orders.createIndex({ customerId: 1 })

// Shard the collection
sh.shardCollection("shop.orders", { customerId: 1 })

// Hashed shard key for even distribution
sh.shardCollection("shop.events", { _id: "hashed" })

// Inspect the cluster
sh.status()
db.orders.getShardDistribution()
sh.isBalancerRunning()

Explanation

Sharding horizontally partitions a collection across multiple shard replica sets, scaling writes and storage. The shard key determines data distribution; hashed keys spread writes evenly, while ranged keys support range queries but can cause hotspots. Choose the key carefully since it cannot be changed easily.

More MongoDB Snippets