Jordi
Jordi

Reputation: 2797

MongoDB balance connections between nodes

Consider the following scenario

MongoDB replica set named myreplica 3 nodes: n1, n2 & n3

the 3 nodes have the same data.

I would like to connect to the 3 nodes and balance the reads from my site. Now I am using this connection string:

mongodb://myuser:mypassword@n1, n2, n3/?replicaSet=myreplica&slaveOk=true

That makes the two slave nodes to work with the reads, but not the primary.

How do I write my connection string in order to query any of the 3 nodes?

source: http://docs.mongodb.org/manual/reference/read-preference/#replica-set-read-preference-modes

UPDATE

With readPreference=nearest option works. The three nodes lives in the same lan.

enter image description here

Upvotes: 3

Views: 425

Answers (1)

Neil Lunn
Neil Lunn

Reputation: 151122

Actually that would not affect your reads at all. All you are really doing is providing a seed list for your connection. And that is all you should be doing in a connect.

In order to decide what your want to do with interaction with reads, you need to set a read preference that is appropriate to what you wish to achieve.

In your case, what you probably want is to set this to secondaryPreferred in order to allow reads from the secondary nodes as well as the primary. But obviously with that precedence.

Also please keep in mind that replica sets are not intended as a scaling option with MongoDB, but rather their purpose is for redundancy and failover.

If you want to distribute performance, then either scale up your hardware, or look into scaling out via implementing Sharding.

Upvotes: 1

Related Questions