Bird
Raised Fist0
MongoDBquery~10 mins

Mongos router behavior in MongoDB - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Mongos router behavior
Client sends query
↓
Mongos receives query
↓
Mongos checks shard key
↓
Shard key present?
No→Broadcast query to all shards
↓
Route query to specific shard
↓
Collect results from shards
↓
Merge and return results to client
Mongos receives queries, checks if shard key is present, routes to specific shard or broadcasts to all, then merges results and returns to client.
Execution Sample
MongoDB
db.collection.find({shardKey: 5, status: 'active'})
Query with shard key routes to one shard; results returned from that shard only.
Execution Table
StepActionShard Key Present?Routing DecisionShards QueriedResult Collected
1Client sends queryYesCheck shard keyN/AN/A
2Mongos receives queryYesRoute to shard with shardKey=5Shard 2N/A
3Shard 2 executes queryN/AN/AShard 2Documents matching query
4Mongos collects resultsN/AN/AShard 2Documents from Shard 2
5Mongos returns results to clientN/AN/AN/AFinal result set
💡 Query routed to shard based on shard key; results returned from that shard only.
Variable Tracker
VariableStartAfter Step 2After Step 4Final
query{shardKey:5, status:'active'}{shardKey:5, status:'active'}{shardKey:5, status:'active'}{shardKey:5, status:'active'}
shardKeyPresentundefinedtruetruetrue
targetShardsundefinedShard 2Shard 2Shard 2
resultsemptyemptydocuments from Shard 2documents from Shard 2
Key Moments - 2 Insights
Why does Mongos route the query to only one shard when the shard key is present?
Because the shard key identifies the exact shard holding the data, Mongos routes the query directly to that shard (see execution_table step 2). This avoids querying all shards and improves efficiency.
What happens if the shard key is missing in the query?
Mongos broadcasts the query to all shards since it cannot determine which shard holds the data. This is less efficient but necessary to find matching documents.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 2, what is the routing decision Mongos makes?
ARoute query to shard with shardKey=5
BBroadcast query to all shards
CReject the query
DCache the query for later
💡 Hint
Check the 'Routing Decision' column at step 2 in the execution_table.
At which step does Mongos collect results from shards?
AStep 3
BStep 4
CStep 1
DStep 5
💡 Hint
Look for the 'Collect results from shards' action in the execution_table.
If the query did not include the shard key, how would the 'Shards Queried' column change at step 2?
AIt would list only one shard
BIt would be empty
CIt would list all shards
DIt would list no shards
💡 Hint
Recall that without shard key, Mongos broadcasts query to all shards.
Concept Snapshot
Mongos router receives client queries.
Checks if shard key is present in query.
If yes, routes query to specific shard.
If no, broadcasts query to all shards.
Collects and merges results before returning to client.
Full Transcript
Mongos acts as a router in a MongoDB sharded cluster. When a client sends a query, Mongos first checks if the query contains the shard key. If the shard key is present, Mongos routes the query directly to the shard that holds the relevant data. This targeted routing improves efficiency by querying only one shard. If the shard key is missing, Mongos broadcasts the query to all shards to find matching documents. After shards execute the query, Mongos collects and merges the results, then returns the final result set to the client. This behavior ensures efficient and correct query routing in a sharded environment.

Practice

(1/5)
1. What is the primary role of the mongos router in a sharded MongoDB cluster?
easy
A. It stores the actual data for the database.
B. It routes queries to the correct shard based on the shard key.
C. It manages user authentication and roles.
D. It backs up the database automatically.

Solution

  1. Step 1: Understand mongos role

    The mongos acts as a query router in a sharded cluster, directing queries to the right shard.
  2. Step 2: Differentiate from other components

    Data storage is handled by shards, not mongos. Authentication and backups are separate concerns.
  3. Final Answer:

    It routes queries to the correct shard based on the shard key. -> Option B
  4. Quick Check:

    mongos routes queries [OK]
Hint: Remember: mongos routes, shards store data [OK]
Common Mistakes:
  • Thinking mongos stores data
  • Confusing mongos with config servers
  • Assuming mongos handles backups
2. Which of the following is the correct way for an application to connect in a sharded MongoDB setup?
easy
A. Connect to the primary replica set member.
B. Connect only to the config servers.
C. Connect directly to each shard individually.
D. Connect to the mongos router.

Solution

  1. Step 1: Identify connection point in sharded cluster

    Applications connect to mongos which routes queries to shards transparently.
  2. Step 2: Exclude other options

    Direct connection to shards or config servers is not recommended; primary replica set member is for replica sets, not sharding.
  3. Final Answer:

    Connect to the mongos router. -> Option D
  4. Quick Check:

    Apps connect to mongos [OK]
Hint: Always connect apps to mongos, not shards [OK]
Common Mistakes:
  • Connecting directly to shards
  • Using config servers for queries
  • Confusing replica sets with sharding
3. Given a sharded cluster with two shards and a mongos router, what will happen when you run this query through mongos?
db.users.find({ userId: 12345 })
Assume userId is the shard key.
medium
A. mongos returns an error because shard key is missing.
B. mongos sends the query to all shards and merges results.
C. mongos routes the query only to the shard containing userId 12345.
D. mongos sends the query to the config servers.

Solution

  1. Step 1: Check query uses shard key

    The query filters on userId, which is the shard key, so mongos can route precisely.
  2. Step 2: Understand mongos routing behavior

    mongos sends the query only to the shard that holds the chunk for userId 12345, not all shards.
  3. Final Answer:

    mongos routes the query only to the shard containing userId 12345. -> Option C
  4. Quick Check:

    Query with shard key routes to one shard [OK]
Hint: Query with shard key goes to one shard only [OK]
Common Mistakes:
  • Assuming mongos queries all shards always
  • Thinking config servers handle queries
  • Believing shard key is optional for routing
4. You wrote a query to find documents by userId in a sharded cluster but get slow results. You realize userId is not the shard key. What is the likely cause?
medium
A. mongos is routing the query to all shards (scatter-gather).
B. mongos is routing the query to only one shard.
C. mongos is ignoring the query and returning empty results.
D. mongos is connecting directly to config servers.

Solution

  1. Step 1: Identify shard key usage in query

    The query filters on userId, which is not the shard key, so mongos cannot route precisely.
  2. Step 2: Understand mongos scatter-gather behavior

    mongos sends the query to all shards (scatter-gather) causing slower results.
  3. Final Answer:

    mongos is routing the query to all shards (scatter-gather). -> Option A
  4. Quick Check:

    Query without shard key causes scatter-gather [OK]
Hint: Queries without shard key hit all shards, slowing response [OK]
Common Mistakes:
  • Assuming query routes to one shard without shard key
  • Thinking mongos returns empty results on missing shard key
  • Confusing config servers with query routers
5. In a sharded MongoDB cluster, you want to optimize query performance for a collection frequently queried by email. The current shard key is userId. What is the best approach involving mongos behavior?
hard
A. Change the shard key to email so mongos routes queries efficiently.
B. Add an index on email and keep the shard key as userId.
C. Connect directly to shards to bypass mongos routing.
D. Disable sharding on the collection to improve query speed.

Solution

  1. Step 1: Analyze query pattern and shard key

    Queries are frequent on email, but shard key is userId, causing scatter-gather queries via mongos.
  2. Step 2: Optimize shard key for routing

    Changing shard key to email lets mongos route queries directly to relevant shards, improving performance.
  3. Final Answer:

    Change the shard key to email so mongos routes queries efficiently. -> Option A
  4. Quick Check:

    Shard key matches query field for efficient mongos routing [OK]
Hint: Match shard key to frequent query field for fast mongos routing [OK]
Common Mistakes:
  • Thinking adding index alone fixes routing
  • Connecting directly to shards bypasses mongos is not recommended
  • Disabling sharding reduces scalability
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard