Skip to content
MongoDB

Sharding

Distribute data across shards by a shard key.

#sharding#scaling#cluster

Code

mongodb
// 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()