0
0
MongoDBquery~5 mins

Mongos router behavior in MongoDB

Choose your learning style9 modes available
Introduction
Mongos acts like a traffic controller that directs database requests to the right place in a sharded MongoDB setup.
When your database is split into parts (shards) to handle lots of data.
When you want to make sure queries go to the correct shard automatically.
When you need to balance the load across multiple servers.
When you want to hide the complexity of multiple shards from your application.
When you want to scale your database horizontally.
Syntax
MongoDB
mongos --configdb <configReplSet>/<host1>:<port1>,<host2>:<port2>,...

// Connect to mongos like a normal MongoDB client
mongo --host <mongos-host> --port <mongos-port>
Mongos is not a database server but a router for sharded clusters.
You connect your application to mongos, not directly to shards.
Examples
Starts a mongos instance connected to the config server replica set.
MongoDB
mongos --configdb configReplSet/localhost:27019,localhost:27020,localhost:27021
Connects to mongos on port 27017 to run queries.
MongoDB
mongo --host localhost --port 27017
Sample Program
This example shows inserting and querying data through mongos. Mongos routes the insert and find commands to the correct shard automatically.
MongoDB
// Assume mongos is running on localhost:27017
// Insert a document into a sharded collection
use shop

// Insert a product
 db.products.insertOne({ _id: 1, name: "Pen", category: "Stationery" })

// Query the product
 db.products.find({ _id: 1 })
OutputSuccess
Important Notes
Mongos does not store data itself; it only routes requests.
It uses metadata from config servers to know where data lives.
If mongos is down, your application cannot access the sharded cluster.
Summary
Mongos routes queries to the right shard in a sharded MongoDB cluster.
Applications connect to mongos, not directly to shards.
Mongos helps scale and balance database load transparently.