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
Insert & Find
Insert documents and query a collection.
Query Operators
Use comparison, logical, array, and regex operators.
Aggregation Pipeline
Build multi-stage pipelines for analytics.
Indexes
Create single, compound, and text indexes for performance.
Update & Delete
Modify and remove documents with update operators.
Collections & Schema
Manage collections, validators, and capped collections.