javamongodbtransactionsmongo-javamongo-java-driver

How many roundtrips are made to a MongoDB server when using transactions?


I wonder how many roundtrips that are made to the server when using transactions MongoDB? For example if the Java driver is used like this:

ClientSession clientSession = client.startSession();
TransactionOptions txnOptions = TransactionOptions.builder()
        .readPreference(ReadPreference.primary())
        .readConcern(ReadConcern.LOCAL)
        .writeConcern(WriteConcern.MAJORITY)
        .build();

TransactionBody txnBody = new TransactionBody<String>() {
    public String execute() {
        MongoCollection<Document> coll1 = client.getDatabase("mydb1").getCollection("foo");
        MongoCollection<Document> coll2 = client.getDatabase("mydb2").getCollection("bar");

        coll1.insertOne(clientSession, new Document("abc", 1));
        coll2.insertOne(clientSession, new Document("xyz", 999));
        return "Inserted into collections in different databases";
    }
};
try {
    clientSession.withTransaction(txnBody, txnOptions);
} catch (RuntimeException e) {
    // some error handling
} finally {
    clientSession.close();
}

In this case two documents are stored in a transaction:

coll1.insertOne(clientSession, new Document("abc", 1));
coll2.insertOne(clientSession, new Document("xyz", 999));

Are the "insert operations" stacked up and sent to the server in one roundtrip or are two calls (or more?) actually made to the server?


Solution

  • Each insert is sent separately. You can use use bulk writes to batch write operations together.

    The commit at the end is a separate operation also.