MongoDB – Properly Connect Replica Set to Split Write and Read

mongodb

As Replica Sets in MongoDB store data in multiple copies for improved data reliability and high service availability.

My Question is that:

How Can I properly connect a replica set to split write and read with ApsaraDB for MongoDB

Best Answer

To correctly connect to a replica set, you must first understand the connection string URI of MongoDB. All official drivers support connection to MongoDB using a connection string.

A connection string includes the following content:

mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]

mongodb:// is a prefix indicating a connection string.

username:password@ indicates the user name and password that must be specified if authentication is enabled.

hostX:portX indicates the IP address and port number of each member in the replica set. Multiple members are separated by commas (,).

/database indicates the database to which the user account belongs during authentication.

?options indicates additional connection options.

To implement read/write splitting, add readPreference=secondaryPreferred to options so that read requests are prioritized to secondary nodes. For more information about read options.

Connections limit: Add maxPoolSize=xx to options to limit the client connection pool to a specified number (xx) of connections.

To confirm writes with the client only after data is successfully written to a majority of nodes, add w= majority to options. For more information about write options.

Connection to ApsaraDB for MongoDB is used as an example here. When you buy an ApsaraDB for MongoDB replica set, you can obtain the name of the replica set and the addresses of replica set members.

For more detailed Answer Please Click Here