How to use clients and client pools.
Create a Client
Single
Basic Usage
void example() {
{
EXPECT(!client);
}
{
EXPECT(client);
}
}
With a Custom URI
void example() {
EXPECT(client);
EXPECT(client.uri().to_string() == uri.to_string());
}
With Client Options
Stable API Options
EXPECT(client);
return client;
}
TLS Options
mongocxx::uri uri{
"mongodb://bob:pwd123@localhost:27017/?tls=true"};
EXPECT(client);
EXPECT(client.uri().to_string() == uri.to_string());
return client;
}
Automatic Encryption Options
R"({"mongocryptdURI": "mongodb://localhost:27027", "mongocryptdSpawnArgs": ["--port", "27027"]})"));
EXPECT(client);
}
APM Options
void example() {
EXPECT(client);
}
Pool
Basic Usage
void example() {
{
EXPECT(entry);
EXPECT(client);
}
{
EXPECT(entry);
EXPECT(client);
}
}
With Client Options
void example() {
EXPECT(entry);
EXPECT(client);
}
Try Acquire
void example() {
mongocxx::uri uri{
"mongodb://localhost:27017/?maxPoolSize=1&waitQueueTimeoutMS=1"};
EXPECT(entry_opt);
EXPECT(*entry_opt);
{
EXPECT(hold);
entry_opt = pool.try_acquire();
EXPECT(!entry_opt);
}
entry_opt = pool.try_acquire();
EXPECT(entry_opt);
EXPECT(*entry_opt);
}
Use a Client
List Databases
int count = 0;
EXPECT(doc["name"]);
EXPECT(doc["sizeOnDisk"]);
EXPECT(doc["empty"]);
if (doc["name"].get_string().value == "admin") {
++count;
}
}
EXPECT(count == 1);
}
List Databases With Options
int count = 0;
EXPECT(doc["name"]);
EXPECT(!doc["sizeOnDisk"]);
EXPECT(!doc["empty"]);
if (doc["name"].get_string().value == "admin") {
++count;
}
}
EXPECT(count == 1);
}
List Database Names
EXPECT(std::count(names.begin(), names.end(), "admin") == 1);
}
List Database Names With Options
EXPECT(std::count(names.begin(), names.end(), "admin") == 0);
}
Error Handling
Invalid Client
void example() {
EXPECT(!client);
try {
EXPECT(false && "should not reach this point");
EXPECT(ex.code() == mongocxx::error_code::k_invalid_client_object);
}
}
Wait Queue Timeout
void example() {
try {
EXPECT(hold);
EXPECT(false && "should not reach this point");
EXPECT(ex.code() == mongocxx::error_code::k_pool_wait_queue_timeout);
}
}
Invalid Stable API Options
void example() {
try {
EXPECT(false && "should not reach this point");
EXPECT(ex.code() == mongocxx::error_code::k_invalid_parameter);
}
try {
EXPECT(false && "should not reach this point");
EXPECT(ex.code() == mongocxx::error_code::k_invalid_parameter);
}
}
TLS Not Enabled
void example() {
try {
EXPECT(false && "should not reach this point");
EXPECT(
ex.code() == mongocxx::error_code::k_invalid_parameter ||
ex.code() == mongocxx::error_code::k_ssl_not_supported ||
false);
}
}
Invalid Auto Encryption Options
void example() {
try {
EXPECT(false && "should not reach this point");
EXPECT(ex.code().value() == 58);
}
try {
EXPECT(false && "should not reach this point");
EXPECT(ex.code().value() == 1);
}
try {
EXPECT(false && "should not reach this point");
EXPECT(ex.code() == mongocxx::error_code::k_invalid_parameter);
}
}