MongoDB C++ Driver mongocxx-4.0.0
Loading...
Searching...
No Matches
Client Sessions

How to create and use client sessions.

Create a Client Session

Basic Usage

void example(mongocxx::client client) {
mongocxx::client_session session = client.start_session();
EXPECT(&session.client() == &client);
EXPECT(session.id()["id"]);
EXPECT(session.id()["id"].type() == bsoncxx::type::k_binary);
EXPECT(session.id()["id"].get_binary().sub_type == bsoncxx::binary_sub_type::k_uuid);
}

With Options

void example(mongocxx::client client) {
mongocxx::options::client_session opts;
opts.snapshot(true);
// ... other client session options.
mongocxx::client_session session = client.start_session(opts);
EXPECT(session.options().snapshot() == true);
}

Use a Client Session

See also

Basic Usage

void example(mongocxx::client_session session, mongocxx::database db) {
mongocxx::collection coll = db.create_collection(session, "coll");
auto x1 = bsoncxx::from_json(R"({"x": 1})");
EXPECT(coll.insert_one(session, x1.view()));
EXPECT(coll.update_one(session, x1.view(), bsoncxx::from_json(R"({"$inc": {"x": 1}})")));
auto doc_opt = coll.find_one(session, make_document());
EXPECT(doc_opt);
auto& doc = *doc_opt;
EXPECT(doc["x"]);
EXPECT(doc["x"].get_int32().value == 2);
}

With Transactions

void example(mongocxx::client_session session, mongocxx::collection coll) {
auto x0 = bsoncxx::from_json(R"({"x": 0})");
auto inc = bsoncxx::from_json(R"({"$inc": {"x": 1}})");
session.start_transaction();
{
auto result_opt = coll.create_bulk_write(session)
.append(insert_one{x0.view()})
.append(insert_one{x0.view()})
.append(insert_one{x0.view()})
.execute();
EXPECT(result_opt);
EXPECT(result_opt->inserted_count() == 3);
}
{
auto result_opt =
coll.update_many(session, bsoncxx::from_json(R"({"x": {"$exists": 1}})"), inc.view());
EXPECT(result_opt);
EXPECT(result_opt->modified_count() == 3);
}
session.commit_transaction();
EXPECT(coll.count_documents(session, bsoncxx::from_json(R"({"x": 1})")) == 3);
}