Skip to content

Instantly share code, notes, and snippets.

@jyemin
Created May 23, 2025 12:28
Show Gist options
  • Save jyemin/81891c53ba571d20757c5f426e8baedc to your computer and use it in GitHub Desktop.
Save jyemin/81891c53ba571d20757c5f426e8baedc to your computer and use it in GitHub Desktop.
import com.mongodb.ClientSessionOptions;
import com.mongodb.client.MongoClients;
import org.bson.Document;
// Demonstration that it's straightforward to implement snapshot reads across sessions,
// clients, and even processes
public static void main() {
var connectionString = "mongodb://localhost/?directConnection=false&writeConcern=majority";
// Enable snapshot reads
var sessionOptions = ClientSessionOptions.builder().snapshot(true).causallyConsistent(false).build();
var client1 = MongoClients.create(connectionString);
var session1 = client1.startSession(sessionOptions);
var coll1 = client1.getDatabase("test").getCollection("causal");
// create a second client and session, simulating multiple processes
var client2 = MongoClients.create(connectionString);
var session2 = client2.startSession(sessionOptions);
var coll2 = client2.getDatabase("test").getCollection("causal");
coll1.drop();
coll1.insertOne(new Document("_id", 1));
// This will obviously find just the one document that was just inserted
var docs = coll1.find(session1).into(new ArrayList<>());
System.out.println(docs);
System.out.println(session1.getSnapshotTimestamp());
// now insert a second document, after the snapshot timestamp is established in session1
coll1.insertOne(new Document("_id", 2));
// Since it's a snapshot read, this will find only the first document
// and the snapshot timestamp will remain the same
docs = coll1.find(session1).into(new ArrayList<>());
System.out.println(docs);
System.out.println(session1.getSnapshotTimestamp());
// Here we copy the snapshot timestamp from the first session into the second,
// establishing the timestamp as equivalent across sessions.
// This is using an API marked as internal only, but still public due to a design quirk
// in the Java driver
session2.setSnapshotTimestamp(session1.getSnapshotTimestamp());
// This will now only find the first document, even though it's the first read
// in scope of session2
docs = coll2.find(session2).into(new ArrayList<>());
System.out.println(docs);
System.out.println(session2.getSnapshotTimestamp());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment