// 2. Tunable consistency controls
|
String connectionString = "mongodb://localhost/?readPreference=secondaryPreferred";
|
|
MongoClient client = new MongoClient(new MongoClientURI(connectionString);
|
|
MongoDatabase database = client.getDatabase("myDatabase");
|
MongoCollection<Document> collection = database.getCollection("myCollection");
|
|
// Start client session, which is causally consistent by default
|
try (ClientSession session = client.startSession(ClientSessionOptions.builder().build())) {
|
//Run causally related operations within the session
|
collection.insertOne(session, ...);
|
collection.updateOne(session, ...);
|
|
try (MongoCursor<Document> cursor = collection.find(session).filter(...).iterator()) {
|
while (cursor.hasNext()) {
|
Document cur = cursor.next();
|
}
|
}
|
}
|