How to Configure MongoDB Routers (mongos) for Query Routing in a Sharded Cluster

MongoDB routers (mongos) are configured for query routing through a startup sequence that verifies config server and shard replica set primaries, launches the mongos process with a config server connection string, and registers shards using sh.addShard() to enable transparent query distribution across the cluster.

The minhhungit/mongodb-cluster-docker-compose repository provides a complete reference implementation for configuring MongoDB routers (mongos) in a containerized sharded environment. This setup demonstrates how mongos instances act as query routers, intercepting client requests and directing them to the appropriate shards based on metadata stored in config servers.

Router Startup Sequence

The mongos configuration is orchestrated by the scripts/entrypoint-route.sh script, which ensures all cluster dependencies are healthy before enabling query routing. This script executes inside the router01 service defined in docker-compose.yml.

Waiting for Config Server Primary

Before mongos can route queries, it must access cluster metadata from the config server replica set. The script waits for a primary to be elected using mongosh to verify replica set status:

mongosh --host rs-config-server/configsvr01:27017,configsvr02:27017,configsvr03:27017 \
        --eval 'rs.status().members.some(m => m.stateStr === "PRIMARY")'

This check, found in scripts/entrypoint-route.sh lines 5-7, ensures the config servers are ready to serve metadata before the router attempts to initialize its routing table.

Waiting for Shard Primaries

The script iterates through each shard replica set (rs-shard-01, rs-shard-02, rs-shard-03) to verify that each has elected a primary before enabling routing:

for shard in 1 2 3; do
    replica_set="rs-shard-0${shard}"
    host_prefix="shard0${shard}"
    ...
    mongosh --host ${replica_set}/${host_prefix}-a:27017,${host_prefix}-b:27017,${host_prefix}-c:27017 \
            --eval 'rs.status().members.some(m => m.stateStr === "PRIMARY")'
done

This validation, located in scripts/entrypoint-route.sh lines 10-16, prevents the router from attempting to route queries to shards that are not yet fully operational.

Launching the mongos Process

Once all dependencies are confirmed healthy, the script launches the mongos process with the --configdb parameter pointing to the config server replica set:

mongos --port 27017 \
       --configdb rs-config-server/configsvr01:27017,configsvr02:27017,configsvr03:27017 \
       --bind_ip_all &

This command, from scripts/entrypoint-route.sh line 21, starts the query router on port 27017 and binds to all network interfaces, allowing client applications to connect transparently.

Registering Shards with sh.addShard()

After mongos starts, the script registers each shard replica set with the cluster using the sh.addShard() command:

sh.addShard("rs-shard-01/shard01-a:27017")
sh.addShard("rs-shard-01/shard01-b:27017")
sh.addShard("rs-shard-01/shard01-c:27017")
// … same for rs-shard-02 and rs-shard-03

These commands, found in scripts/entrypoint-route.sh lines 32-40, populate the config server metadata with shard topology information. This registration enables mongos to maintain the chunk-to-shard mapping required for routing queries to the correct data locations.

Key Configuration Components

Understanding how mongos handles query routing requires examining the specific configuration parameters that connect it to the cluster topology.

Config Server Connection String

The --configdb parameter is the critical configuration element that enables query routing. It specifies the config server replica set name (rs-config-server) and member addresses:


rs-config-server/configsvr01:27017,configsvr02:27017,configsvr03:27017

This connection string allows mongos to read chunk distribution metadata and determine which shard holds data for a given query. According to the repository's implementation, mongos caches this metadata and refreshes it periodically to maintain accurate routing tables.

Replica Set Awareness

By specifying replica set names in the connection strings (e.g., rs-shard-01), mongos maintains awareness of shard topology. This enables automatic failover—if a shard primary becomes unavailable, mongos detects the new primary election through the replica set protocol and redirects queries accordingly.

The repository demonstrates this by registering all replica set members via sh.addShard() in scripts/entrypoint-route.sh, ensuring mongos has complete visibility into each shard's member set for robust query routing.

Network Binding and Port Configuration

The --bind_ip_all flag configures mongos to accept connections on all network interfaces, while --port 27017 maintains the standard MongoDB port. This configuration, implemented in scripts/entrypoint-route.sh line 21, allows client applications to connect to the router transparently without knowing the underlying shard architecture.

Client Connection Examples

Once configured, mongos presents a single endpoint that routes queries automatically to the appropriate shards based on the shard key.

Shell Connection

Clients connect to the router exactly as they would to a standalone MongoDB instance:

mongosh --host router-01 --port 27017

From the client's perspective, the sharded cluster appears as a single database. The mongos instance handles all routing logic internally, directing queries to the appropriate shards based on the shard key ranges stored in its cached metadata.

Application Code Example

The repository includes a C# client example in client/DemoMongoClusterReader/Program.cs that demonstrates connecting to the router:

var client = new MongoClient("mongodb://router-01:27017");
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("mycoll");

// Queries are automatically routed to the correct shard
var result = await collection.Find(Builders<BsonDocument>.Filter.Empty).ToListAsync();

This example illustrates that applications require no special configuration for sharding—they simply connect to the mongos router endpoint, and the router handles query distribution transparently.

Summary

  • Startup Orchestration: The scripts/entrypoint-route.sh script configures mongos by first verifying that config servers and all shard replica sets have elected primaries, ensuring the cluster is ready for routing.

  • Config Server Dependency: Mongos uses the --configdb parameter to connect to the rs-config-server replica set, reading chunk metadata that determines how to route queries to the correct shards.

  • Shard Registration: The sh.addShard() commands in the entrypoint script register each shard replica set (rs-shard-01, rs-shard-02, rs-shard-03) with the cluster metadata, enabling mongos to distribute queries across the topology.

  • Transparent Client Access: Once configured, mongos exposes a standard MongoDB endpoint on port 27017, allowing client applications to connect without awareness of the underlying shard architecture.

Frequently Asked Questions

What is the role of mongos in a sharded MongoDB cluster?

Mongos acts as a query router that intercepts client requests and directs them to the appropriate shards containing the requested data. It maintains cached metadata from the config servers about which shard holds which chunks of data based on shard key ranges. This allows mongos to route queries transparently without requiring client applications to know the physical location of data.

How does mongos know which shard contains the data for a specific query?

Mongos reads cluster metadata from the config server replica set specified in the --configdb parameter. This metadata includes the shard key ranges for each chunk of data and which shard hosts each chunk. When a query arrives, mongos compares the query's shard key against the cached chunk distribution to determine the target shard. For queries without a shard key, mongos performs a scatter-gather operation across all shards.

Why must mongos wait for config servers and shards to elect primaries before starting?

Mongos requires a primary in the config server replica set to read the authoritative cluster metadata and write routing table updates. Without a config primary, mongos cannot initialize its routing table or register new shards. Similarly, mongos waits for shard primaries to ensure the cluster is fully operational before accepting client connections, preventing routing errors to unavailable shards. The scripts/entrypoint-route.sh script implements these health checks using mongosh commands that verify rs.status().members.some(m => m.stateStr === "PRIMARY").

Can I run multiple mongos instances for high availability?

Yes, you can deploy multiple mongos instances to eliminate single points of failure and distribute client connection load. Each mongos instance operates independently and maintains its own cache of the config server metadata. In the minhhungit/mongodb-cluster-docker-compose repository, you could replicate the router01 service definition in docker-compose.yml to create additional router instances, each running the same scripts/entrypoint-route.sh initialization logic. Client applications can then connect to any available mongos instance using a connection string that lists multiple router hosts.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →