Replication.
Sharding.
Replication
Replication is the process of creating and managing a duplicate version of a database across servers to provide redundancy and increase availability of data.
Recipe 5-1. Set Up a Replica Set
In this recipe, we are going to discuss how to set up a replica set (one primary and two secondaries) in Windows.
Problem
You want to create a replica set.
Solution
Use a group of mongod instances.
How It Works
Let’s follow the steps in this section to set up a three-member replica set.
Step 1: Three-Member Replica Set
Note
hostname must be replaced as with ipaddress or localhost if it is the same local machine.
Refer to Figure 5-5 for a mongod instance that is waiting for connection on port 20002.
Here, the mongod instance running on port 20001 becomes primary.
The output Error: error: { ........... } shows that we are getting an error message because we are trying to read data from the secondary node.
In the preceding output, WriteCommandError { ........... } shows that we are getting an error message because we can’t perform write operations in a secondary node. We can perform write operations only in the primary node.
Step 2: Auto Failover—High Availability
Sharding
Vertical scaling: We need to increase the capacity of a single server such as using a more powerful CPU, adding more RAM, or increasing the amount of storage space.
Horizontal scaling: We need to divide the data set and distribute the workload across the servers by adding additional servers to increase the capacity as required.
- 1.
Shard: Each shard contains a subset of the sharded data. Each shard can be deployed as a replica set.
- 2.
mongos: The mongos acts as a query router, providing an interface between client applications and the sharded cluster.
- 3.
Config servers: Config servers store metadata and configuration settings for the cluster.
Recipe 5-2. Sharding
In this recipe, we are going to discuss how to create sharding to distribute data across servers.
Problem
You want to create sharding to distribute data across servers.
Solution
The solution is a group of mongod instances .
How It Works
Let’s follow the steps in this section to set up a sharding.
Step 1: Sharded Cluster
First, create data directories for three shards as shown here.
Next, start the shards as shown here.
Now it is time to perform sharding. Here, we are going to use one query router, one config server, and three shards.
This shows that user data is distributed to shard1 and shard2.
Note
All these demos are executed in a Windows environment.