distributed query:MongoDB's distributed model is divided into replica set and sharded cluster.
The read operation is highly efficient by forwarding read from the Sharding key (sharding key) to the specified shard node in the sharded cluster, but if the query does not contain sharding key, then this read will be forwarded to all Shard nodes and MONGOs Server is responsible for the merge results (including sorting), so this situation is poor performance (commonly known as scatter, gather), for large clusters, this kind of query is usually not feasible.
For replica set, it only involves routing the read operation to which secondary, by default, the read request always occurs on primary, and we can adjust this behavior by specifying "read Preference Mode".
Java code
The code above indicates as much as possible to read from the secondary, if all secondary are invalidated, read from the primary. "Read and write separation" can be achieved.
The currently supported read mode:
1) Primary: The read operation only occurs on primary, the default read mode. If the primary fails, the error is returned.
2) primarypreferred: The read operation occurs on primary, and if the primary fails, it is received by the secondary read request. This is a relatively good pattern,
3) Secondary: Read operation only occurs on secondary, if the desired oh secondary is invalid, then return error.
4) Secondarypreferred: Read operations usually occur on secondary, and if all secondary are invalidated, then primary receives the read request.
5) Nearest: Read the "nearest" node, MongoDB client will evaluate the network latency with each node, the node with the least limited selection delay, primary and secondary are likely to receive read requests (different clients may be delayed differently).
MongoDB distributed Query