Search code examples
javamongodbdocumentationreplicationmongodb-java

What will happen if create MongoClientURI from URI containing multiple hosts, but not a replicaSet option?


From MongoClientURI documentation:

Represents a URI which can be used to create a MongoClient instance. The URI describes the hosts to be used and options. The format of the URI is:

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

-

host1 is the only required part of the URI. It identifies a server address to connect to.

-

Replica set configuration:

replicaSet=name: Implies that the hosts given are a seed list, and the driver will attempt to find all members of the set.

I wonder, is there any sense in passing multiple hosts without specifying replicaSet? Will Mongo client discover the replica set if I pass all nodes hosts but forget to specify replicaSet?


Solution

  • The same could essentially be said of passing a "seed list" of replica set members but not all of the members of the set. The driver will essentially "query" the first available member in order to determine information about the replica set.

    This allows things such as where the first member or even none of the mentioned members are in fact the current PRIMARY. The information returned then tells the driver what all of the members are and of course which one is presently the PRIMARY, as that at least will always be needed for writes.

    The other case here is of course where there are multiple "routers" or "mongos" instances for a sharded cluster. Specifying more that one in the list of hosts would result in one of those hosts being chosen at the time of connection as the point being connected to. In the event of an error in that connection, and where you are handling this, subsequent attempts would then pick up the "first available" host and use that for the connection.

    That fairly much covers the various cases where you can have more than one host in your URI connection.