Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create transactions using MongoDB Java?

I am working in java (not is spring) on a mongo db collection. I want to perform some update operations in one transaction, so all or none of the operations will be execute.
I didn't find any simple example of how it can be done. I understand that it related to session in mongo db, but how to create this session? If someone have an example of this scenario in java I will appreciate if he could share.

Thanks, Osnat.

like image 330
Osnat Avatar asked Oct 23 '25 12:10

Osnat


1 Answers

There's a complete example in the mongodb 4 documentation, here.

The usage pattern looks like this:

ClientSession session = client.startSession();
        try {
            session.startTransaction(  ... some tranaction options ... ).build());
            // manipulate data
            session.commitTransaction();
        } catch (MongoCommandException e) {
            session.abortTransaction();
        } finally {
            session.close();
    }
like image 150
Curiosa Globunznik Avatar answered Oct 26 '25 03:10

Curiosa Globunznik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!