Example usage for com.mongodb.client MongoClient startSession

List of usage examples for com.mongodb.client MongoClient startSession

Introduction

In this page you can find the example usage for com.mongodb.client MongoClient startSession.

Prototype

ClientSession startSession(ClientSessionOptions options);

Source Link

Document

Creates a client session.

Usage

From source file:documentation.CausalConsistencyExamples.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * @param args takes an optional single argument for the connection string
 *///w  w  w.  ja  v  a2s .c o m
public static void main(final String[] args) {
    setupDatabase();
    MongoClient client = MongoClients.create();

    // Start Causal Consistency Example 1
    // Example 1: Use a causally consistent session to ensure that the update occurs before the insert.
    ClientSession session1 = client
            .startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
    Date currentDate = new Date();
    MongoCollection<Document> items = client.getDatabase("test").withReadConcern(ReadConcern.MAJORITY)
            .withWriteConcern(WriteConcern.MAJORITY.withWTimeout(1000, TimeUnit.MILLISECONDS))
            .getCollection("test");

    items.updateOne(session1, eq("sku", "111"), set("end", currentDate));

    Document document = new Document("sku", "nuts-111").append("name", "Pecans").append("start", currentDate);
    items.insertOne(session1, document);
    // End Causal Consistency Example 1

    // Start Causal Consistency Example 2
    // Example 2: Advance the cluster time and the operation time to that of the other session to ensure that
    // this client is causally consistent with the other session and read after the two writes.
    ClientSession session2 = client
            .startSession(ClientSessionOptions.builder().causallyConsistent(true).build());
    session2.advanceClusterTime(session1.getClusterTime());
    session2.advanceOperationTime(session1.getOperationTime());

    items = client.getDatabase("test").withReadPreference(ReadPreference.secondary())
            .withReadConcern(ReadConcern.MAJORITY)
            .withWriteConcern(WriteConcern.MAJORITY.withWTimeout(1000, TimeUnit.MILLISECONDS))
            .getCollection("items");

    for (Document item : items.find(session2, eq("end", BsonNull.VALUE))) {
        System.out.println(item);
    }
    // End Causal Consistency Example 2
}