I am new to mongo db i am trying to write documenst to different collection in same database and maintaining atomicity through transaction feature in mongodb in case of exception it should rollback all the data written. I have list with tuple2 containing collection name and document like below
Tuple2<CollectionName,Document> doc1;
Tuple2<CollectionName,Document> doc2;
List<doc1,doc2>;
ClientSession clientSession = mongoClient.startSession();
try {
clientSession.startTransaction(TransactionOptions.builder().writeConcern(WriteConcern.MAJORITY).build());
for (Tuple2<String, String> myDocument: DocumentList) {
MongoDatabase db = mongoClient.getDatabase("mydb");
MongoCollection<Document> collection = db.getCollection(myDocument.f0);
Document event = Document.parse(myDocument.f1);
collection.insertOne(clientSession, event);
}
}
catch (MongoCommandException | MongoWriteException exception) {
clientSession.abortTransaction();
log.error("Exception happened while inserting record into Mongo DB rolling back the transaction and cause of exception is:%s", ExceptionUtils.getStackTrace(exception)));
}
clientSession.commitTransaction();
}
I am getting below error
The full response is {“ok”: 0.0, “errmsg”: "Error=2, Details='Response status code does not indicate success: BadRequest (400); Substatus: 1101; ActivityId: f689251a-3e97-40e1-843a-6f339d7b2554; Reason: (Message: {“Errors”:[“Transaction is not active”]}\r\nActivityId: f689251a-3e97-40e1-843a-6f339d7b2554, Request URI: /apps/1db5759c-505a-463f-9614-5d39ab12da22/services/c45af58e-eb23-4f44-8707-a4242a082f54/partitions/da75cb38-62d2-4415-a81a-4d9a4a1b4fd7/replicas/132950835021485319p/, RequestStats:
But if i move the clientSession.commitTransaction(); to for loop it will commit the data but in case of transaction failure it is not rolling back the data already written