0

I am using Kotlin, Kmongo and Ktor for my server app to manage MongoDB.

Here is one function that uses transactions:

var txnOptions: TransactionOptions = TransactionOptions.builder()
        .readPreference(ReadPreference.primary())
        .readConcern(ReadConcern.LOCAL)
        .writeConcern(WriteConcern.MAJORITY)
        .build()


runBlocking {

    client.startSession().use { session ->

        session.startTransaction(txnOptions)

        try {

            collection.updateOneById(
                clientSession = session,
                id = "validIdName", // matched with a valid field name so this will be successful
                update = set("validFieldName", "999")
            ).wasAcknowledged() 

            collection.updateOneById(
                clientSession = session,
                id = "invalidIdName", // invalid id so this will not be executed
                update = set("validFieldName", "999")
            ).wasAcknowledged()

            session.commitTransactionAndAwait()

        } catch (e: MongoCommandException) {
            functionSuccessful = false
            session.abortTransaction()
            throw error(e.localizedMessage ?: e)
        } finally {
            session.close()
        }
    }
}

So I expect both write operations to fail because the 2nd operations has an invalid id match name. When this functions executes, the 1st write operation goes through the 2nd one does not.

This is not what I expected from transactions, I want both to fail despite the 1st write being matched properly.

Anudeep Ananth
  • 955
  • 1
  • 8
  • 30

0 Answers0