How to create and use URIs.
- See also
-
Create a URI
Basic Usage
void example() {
const auto uri_str = "mongodb://bob:pwd123@localhost:27017/?tls=true";
EXPECT(uri.to_string() == uri_str);
EXPECT(uri.username() == "bob");
EXPECT(uri.password() == "pwd123");
EXPECT(uri.tls() == true);
}
Default Value
void example() {
const auto uri_str = "mongodb://localhost:27017";
EXPECT(a.to_string() == uri_str);
EXPECT(b.to_string() == uri_str);
EXPECT(c.to_string() == uri_str);
}
Query a URI
User Credentials
void example() {
{
EXPECT(uri.username().empty());
EXPECT(uri.password().empty());
EXPECT(uri.tls() == false);
}
{
mongocxx::uri uri{
"mongodb://bob:pwd123@localhost:27017/?tls=true"};
EXPECT(uri.username() == "bob");
EXPECT(uri.password() == "pwd123");
EXPECT(uri.tls() == true);
}
}
List of Hosts
void example() {
mongocxx::uri uri{
"mongodb://127.0.0.1,[::1]:27018,%2Fpath%2Fto.socket:27019"};
std::vector<mongocxx::uri::host> hosts = uri.hosts();
EXPECT(hosts.size() == 3u);
const mongocxx::uri::host& first = hosts[0];
const mongocxx::uri::host& second = hosts[1];
const mongocxx::uri::host& third = hosts[2];
EXPECT(first.name == "127.0.0.1");
EXPECT(first.port == 27017u);
EXPECT(first.family == 0);
EXPECT(second.name == "::1");
EXPECT(second.port == 27018u);
EXPECT(second.family != 0);
EXPECT(third.name == "/path/to.socket");
EXPECT(third.port == 27019u);
EXPECT(third.family != 0);
}
Optional Options
void example() {
{
std::string database = uri.database();
EXPECT(database.empty());
auto try_once_opt = uri.server_selection_try_once();
EXPECT(!try_once_opt);
auto appname_opt = uri.appname();
EXPECT(!appname_opt);
}
{
mongocxx::uri uri{
"mongodb://localhost:27017/dbName?appName=example&retryReads=true"};
auto database = uri.database();
EXPECT(database == "dbName");
auto retry_reads_opt = uri.retry_reads();
EXPECT(retry_reads_opt);
EXPECT(*retry_reads_opt == true);
auto appname_opt = uri.appname();
EXPECT(appname_opt);
EXPECT(appname_opt->compare("example") == 0);
}
}
All URI Options
void example() {
mongocxx::uri uri{
"mongodb://localhost:27017/?appName=example&tls=true&maxPoolSize=10"};
EXPECT(options["appname"]);
EXPECT(options["appname"].get_string().value == "example");
EXPECT(options["tls"]);
EXPECT(options["tls"].get_bool().value == true);
EXPECT(options["maxpoolsize"]);
EXPECT(options["maxpoolsize"].get_int32().value == 10);
}
Error Handling
Invalid URI
void example() {
try {
EXPECT(false && "should not reach this point");
EXPECT(ex.code() == mongocxx::error_code::k_invalid_uri);
}
try {
EXPECT(false && "should not reach this point");
EXPECT(ex.code() == mongocxx::error_code::k_invalid_uri);
}
try {
mongocxx::uri invalid_uri{
"mongodb://localhost:27017/?authMechanism=SCRAM-SHA-256"};
EXPECT(false && "should not reach this point");
EXPECT(ex.code() == mongocxx::error_code::k_invalid_uri);
}
}