Unable to make transactions to work

I am unable to make the transactions to work in python. Looked at the example scripts, read documentation. I know I am missing something. Appreciate your help.

The error is Database has no attribute ‘_retryable_write’. To access the _retryable_write collection, use database[’_retryable_write’].

Here is the code

        client = pymongo.MongoClient(db_string)
        airbnb = client.get_database("sample_airbnb")
        session = client.start_session()
        transaction_collection = pymongo.collection.Collection(client, "gmm_transaction", session=session)
        result = transaction_collection.insert_one({
        "transaction_id": "x",
        "product_id": "y",
        "cost": 12.34,
        "split_percent": 0.23,
        "designated_buyer_id": "Ram",
        "designated_receiver_id": "Lakshman",
        "buy_type": 1,
        "reference": "xys",
        "status": 1,
        "created_dt": datetime.now().strftime("%d/%m/%Y %H:%M:%S")
     }, session=session)
        return airbnb
    except errors.PyMongoError as e:
        print("The error message is ", e)
        return None
    except Exception as e:
        print("The generic error is", e)
        return None

I have added “retryWrites=true” to the connection string as well.

Thanks for your help

Can anyone help here?

My connect string is mongodb+srv://:@gemiftcluster.qwn4p.mongodb.net/sample_airbnb?retryWrites=true&w=majority

Hi @Saravana_Srinivasan ,

It’s been a while since you posted this question, have you found a solution to the problem ?

The error message is related to your line of code:

transaction_collection = pymongo.collection.Collection(client, "gmm_transaction", session=session)

In order to instantiate a collection instance you need to fetch it from a database instance i.e. airbnb variable. For example:

transaction_collection = airbnb.transaction_test

See also PyMongo: Getting A Collection

In addition to the above, you should structure your code as:

client = pymongo.MongoClient(db_string)
collection = client.sample_airbnb.gmm_transaction
with client.start_session() as session:
    with session.start_transaction():
        collection.insert_one({"transaction_id":"x", "product_id":"y"}, session=session)

See also PyMongo: Transactions and MongoDB Transactions for more information.


1 Like