1

My code is like this:

Replset = {<<"rs1">>, [{localhost, 27017}, {localhost, 27018}, {localhost, 27019}]},
  Conn_Pool = resource_pool:new (mongo:rs_connect_factory(Replset), 10),
  ...

  Conn = resource_pool:get(Conn_Pool)
  case mongo:do(safe, master, Conn, ?DATABASE,
    fun() ->
     mongo:insert(mytable, {'_id', 26, d, 11})
  end end)
  ...

27017 is the primary node, so ofc I can insert the data successfully.

But, when I put only one secondary node in the code instead of all of mongo rs instances: Replset = {<<"rs1">>, [{localhost, 27019}]}, I can also insert the data.

I thought it should have thrown exception or error, but it had written the data successfully.

why that happened?

NetStarter
  • 3,189
  • 7
  • 37
  • 48
Mark_H
  • 770
  • 1
  • 6
  • 19

1 Answers1

1

When you connect to a replica set, you specify the name of the replSet and some of the node names as seeds. The driver connects to the seed nodes in turn and discovers the real replica set membership/config/status via 'db.isMaster()' command.

Since it discovers which node is the primary that way, it is able to then route all your write requests accordingly. The same technique is what enables it to automatically failover to the newly elected primary when the original primary fails and a new one is elected.

Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133
  • So will the connection be created between the erlang server to {localhost, 27019} or {localhost, 27017} when I write data into db? I mean, the data will go "27019" first, and then mongo instance will pass the data to "27017"(cause I put 27019 as the only seed); or erlang server will get config info of mongo relica sets, then find the primary node and build a connection with 27017, and then write the data directly to 27017? – Mark_H May 21 '13 at 09:33
  • connection is created by the driver to each non-hidden member of a replica set. Writes will always go to whichever of them is the primary. So the latter, but it doesn't just build connection to primary, it maintains connections to all members of replica so it can do proper failover if primary disappears. – Asya Kamsky May 21 '13 at 12:48