Mongocxx : Understanding transactions

Hello everyone,

Sorry if I’m clear enough, it’s my first post on this forum. Here’s my situation : I try to understand how the transactions works with the mongocxx driver. I try the following code :

mongocxx::instance instance {};
mongocxx::uri mongouri("mongodb://localhost:27017/?replSet=myReplicaSet");
mongocxx::pool mongopool(mongouri);

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    auto client = mongopool.acquire();
    auto session = client->start_session();


    mongocxx::options::transaction txn_opts;
    mongocxx::read_concern rc;
    mongocxx::write_concern wc;
    mongocxx::read_preference rp;

    rp.mode(mongocxx::read_preference::read_mode::k_primary);
    rc.acknowledge_level(mongocxx::read_concern::level::k_snapshot);
    wc.acknowledge_level(mongocxx::write_concern::level::k_majority);
    txn_opts.read_concern(rc);
    txn_opts.write_concern(wc);

    session.start_transaction(txn_opts);

    auto coll = session.client().database("MongoLibTest")["transaction"];

    coll.insert_one(make_document(kvp("test","testTransaction")));

    session.abort_transaction();

    return a.exec();
}

When I execute this, I have a document that is inserted in my collection. Is it normal as I abort the collection ?
I’m running on a Mongo 5.0.14 server. The server is configured as a replica set with a single node.
I use the driver mongocxx 3.6.

Thanks a lot for your help,

The session needs to be passed to each operation in the transaction. Try passing session as an argument to coll.insert_one.

Thank you ! I wasn’t attentive enough …
It solved my issue directly.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.