Problem Statement
What is the role of mongos in a sharded cluster?
Explanation
Mongos is the query router in a sharded cluster. It provides the interface between client applications and the sharded cluster, receiving queries and routing them to the appropriate shard or shards.
Applications connect to mongos instances, not directly to shards. Mongos uses metadata from config servers to determine which shards contain the requested data. It then routes the query, gathers results from multiple shards if needed, and returns the merged results to the client. Multiple mongos instances can run for high availability.
Code Solution
SolutionRead Only
// Application connects to mongos, not shards
mongo "mongodb://mongos1.example.net:27017"
// Mongos routes query to correct shard(s)
db.users.find({ userId: 12345 })
// Mongos checks shard key range
// Routes to Shard 2 (contains userId 10000-20000)
// Query spanning multiple shards
db.users.find({ age: { $gt: 25 } })
// Mongos sends to all shards, merges results