Search code examples
mongodbreplicationsharding

how to execute read only query on sharded replica set in mongodb


Consider following configuration -

  1. 2 Shard server each has 1-replica set (say rs0 and rs1).
  2. 3 config server and 1 query router (mongos)

The above sharding configuration is working fine. But, i want to execute read-only query from sharded replica set (from secondary of rs0 and rs1). Since, the mongodb data are exists in both replica set rs0 and rs1. So, how to configure this, to fetch the data from both secondary of rs0 and rs1?.


Solution

  • Your sharding setup should not impact the use of read preferences, so you can continue to use Secondary or SecondaryPreferred to access the secondaries of your replica sets within each shard:

    Read Preference in Sharded Clusters

    Changed in version 2.2: Before version 2.2, mongos did not support the read preference mode semantics.

    In most sharded clusters, each shard consists of a replica set. As such, read preferences are also applicable. With regard to read preference, read operations in a sharded cluster are identical to unsharded replica sets.

    Unlike simple replica sets, in sharded clusters, all interactions with the shards pass from the clients to the mongos instances that are actually connected to the set members. mongos is then responsible for the application of read preferences, which is transparent to applications.

    There are no configuration changes required for full support of read preference modes in sharded environments, as long as the mongos is at least version 2.2. All mongos maintain their own connection pool to the replica set members. As a result:

    • A request without a specified preference has primary, the default, unless, the mongos reuses an existing connection that has a different mode set. To prevent confusion, always explicitly set your read preference mode.

    • All nearest and latency calculations reflect the connection between the mongos and the mongod instances, not the client and the mongod
      instances. This produces the desired result, because all results must pass through the mongos before returning to the client.

    http://docs.mongodb.org/manual/core/read-preference-mechanics/