Mongo transaction rollback

In many programs, we need to roll back additions, deletions, changes, etc. that have been completed because of errors or terminations in the program. MongoDB cannot be rolled back when only one host is deployed. Therefore, the MongoDB replica set needs to be built first. Docker MongoDB Replication can be viewed here blog.csdn.net/weixin_4285…

Connect to the master node of the MongoDB replica set.

importPymongo.mongoclient = pymongo.mongoclient (pymongo.mongoclient)'192.168.1.75'.27017Database = client['Demo'] # database = database['demo']
Copy the code

Transaction rollback mode one: Rollback data when the program fails or terminates due to abnormal data.

A:

Session = client.start_session(causal_consistency=True) # create transaction session(causal_consistency=True session.start_transaction()tryCollection.insert_one ({'0': 'Insert data properly'}, session=session) # collection.insert_one({0: 'Abnormal insert data'}, session=session) # raise ValueError'Throw an error')
    
except Exception asSession.abort_transaction () print(e)elseSession.mit_transaction ()finally: # close transaction session session.end_session()Copy the code

Method 2:

tryDefault Causal_consistency =True to maintain causal_consistencywith client.start_session(causal_consistency=True) asSession: # Start transaction sessionwithSession.start_transaction (): # collection.insert_one({'0': 'Insert data properly'}, session=session) # collection.insert_one({0: 'Abnormal insert data'}, session=session) # raise ValueError'Throw an error')
            
except Exception asPrint (e)Copy the code

The above two programs have a normal data insertion at the beginning, and then the data program will stop because of data exception error or program error. The transaction will roll back to the state before the program, and there will be no program execution failure, but some data is inserted, resulting in data disorder.

Where data is added, deleted and modified in the program, MongoDB transactions can be used to prevent data inconsistency with execution results due to abnormal data or program errors, so as to ensure the consistency of the program.

Insert operation can be rolled back. Update operation cannot be rolled back

Insert rollback is supported, update rollback is not supportedfrom pymongo import MongoClient


connect_str = 'mongodb://username:paaword@ip:port,ip:port',

db_name = 'db_name'Mongodb_db = MongoClient [db_name] occupy_col = client_db['user_occupy']
order_col = client_db['user_order']




if __name__ == "__main__": Session = client.start_session(causal_consistency=True session.start_transaction()try:
        res = occupy_col.update_one(
            {"occupy_id": 'occ_3565DbcBE426'},
            {'$set': {'occupy_count': 15}}
        )
        # res = occupy_col.insert_one({'name': 'xiaoming'}, session=session)

        print(f"res = {res}")
        import time
        time.sleep(15)
        print(aaaaa)

        res2 = occupy_col.update_one(
            {"occupy_id": 'occ_fc07569326E8'},
            {'$set': {'occupy_count': 15}}
        )

        print(f"res2 = {res2}")
        # res = order_col.insert_one({'name': 'xiaoming'}, session=session)

    except:
        importTraceback traceback.print_exc() # print(f"Abnormal operation, interrupted transaction")
        session.abort_transaction()
    else:
        print('commit --- ')
        session.commit_transaction()
    finally:
        print('finally ---')
        session.end_session()
Copy the code
Copy the code