JT PRAK
JT PRAK

Reputation: 1

how to insert data when one of muliple binding ips is diconnected on mongodb?

I have 2 PC set including 2 lan ports for each PC. I've made setting for using replSet.

PC No.1

mongod --bind_ip 127.0.0.1,192.168.0.231,192.168.0.241 --replSet repl --dbpath C:\mongodb\data --port 27017

PC No.2

mongod --bind_ip 127.0.0.1,192.168.0.232,192.168.0.242 --replSet repl --dbpath C:\mongodb\data --port 27017

config = {_id : "repl", members : [{_id:0, host:"192.168.0.231:27017", priority:1},{_id:1, host:"192.168.0.232:27017", priority:1}]};

rs.initiate(config);

mongosh --host 192.168.0.241 --port 27017

I can read all data with both IPs(192.168.0.231,192.168.0.241). but i can not receive any result with IP 192.168.0.241 when i use command for "insertOne()" with disconnected with IP 192.168.0.231

and i also can not read any data from my APP with mongo drive with same condition.

plese give your any advice.

Upvotes: 0

Views: 46

Answers (1)

user20042973
user20042973

Reputation: 5090

I think there are a few different concepts being conflated here resulting in a bit of confusion and inconsistent behavior. The short answer is that the application should be using a connection string for the replica set rather than a standalone server in order to function properly.

The bind_ip setting describes what network interfaces the mongod processes should use to listen for connections. If the members of the replica set are communicating with each other (e.g. rs.initiate(config); was successful) and the client application can also connect to all members of the replica set, then the binding is properly configured and there are no changes or problems there.

What is happening instead is that you are connecting directly to the members of the replica set individually. Assuming the replica set is functioning properly, one of the two members will be in the PRIMARY state and the other will be a SECONDARY. While both can serve read operations, only the PRIMARY can accept writes. This seems to be similar to the behavior that you are describing.

The fact that Mongosh can read data from both members but your application can only read from one probably relates to read preference. By default, drivers will use a read preference of primary but Mongosh will probably automatically configure reads from other members when connected directly.

Therefore you should configure your application to use an appropriate connection URI. This should specifically include the replica set options as well as read preference if you would like to read from any members. The connection string would probably look something like the following in your situation:

mongodb://192.168.0.231:27017,192.168.0.232:27017/?replicaSet=repl&readPreference=primaryPreferred

Upvotes: 0

Related Questions