Intermediate LevelMongoDB & Mongoose
What is MongoDB Sharding and how does shard key selection impact cluster scaling?
❓ Interview Prompt: Explain Sharded Clusters (Mongos Router, Config Servers, Shards), Shard Keys, range vs hashed sharding, jumbo chunks, and hotspots.
Sharding is MongoDB's horizontal scaling solution that distributes collection documents across multiple server clusters (Shards):
Architecture:
•
Mongos Router: Query router that routes client operations to target shards.
•
Config Servers: Store cluster metadata and chunk mappings.
•
Shard Key: Immutable indexed field(s) determining document partition placement. High-cardinality shard keys prevent jumbo chunks and single-shard hotspots!
Code Implementation Example
typescript
import mongoose from 'mongoose';
// Sharding collection by hashed userId shard key
async function configureCollectionSharding() {
const adminDb = mongoose.connection.db!.admin();
await adminDb.command({
enableSharding: 'ecommerce'
});
await adminDb.command({
shardCollection: 'ecommerce.orders',
key: { userId: 'hashed' }
});
}💡Configuring collection sharding with a hashed shard key.
🎯 Interview Key Takeaway
Choose high-cardinality, well-distributed shard keys to ensure balanced data routing across sharded cluster nodes.
#Sharding#Shard Key#Mongos#Horizontal Scaling#Intermediate
Back to all MongoDB & Mongoose Questions→