1. Configuration parameters
primary: The default parameter, only read from the primary node;
primaryPreferred: Most of the data is read from the primary node, and only when the primary node is unavailable, data is read from the secondary node.
Secondary: Only read from the secondary node. The problem is that the data of the secondary node will be "older" than the data of the primary node.
secondaryPreferred: read from the secondary node first, and read data from the primary node when the secondary node is unavailable;
nearest: regardless of whether it is the primary node or the secondary node, read data from the node with the lowest network delay.
2. Configuration method
Original: mongodb://username:password@IP:port,P:port,P:port,/?authSource=library name
After modification: mongodb://username:password@IP:port,P:port,P :port,/?authSource=library name&readPreference=secondaryPreferred
3、demo
package com.ucia.demo;
import org.bson.Document;
import com.mongodb.BasicDBObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class test {