How to obtain and use databases.
Obtain a Database
EXPECT(db);
EXPECT(db.name() == "db");
EXPECT(client.database("db").name() == "db");
}
Database Operations
Drop a Database
{
std::vector<std::string> names = client.list_database_names();
EXPECT(std::count(names.begin(), names.end(), "db") == 1);
}
db.drop();
{
std::vector<std::string> names = client.list_database_names();
EXPECT(std::count(names.begin(), names.end(), "db") == 0);
}
}
Run a Command
EXPECT(reply["ok"]);
EXPECT(reply["ok"].get_double().value == 1.0);
}
Set a Read Concern
using rc_level = mongocxx::read_concern::level;
{
EXPECT(rc.acknowledge_level() == rc_level::k_server_default);
}
{
rc.acknowledge_level(rc_level::k_majority);
db.read_concern(rc);
EXPECT(db.read_concern() == rc);
EXPECT(db.read_concern().acknowledge_level() == rc_level::k_majority);
}
}
Set a Write Concern
using wc_level = mongocxx::write_concern::level;
{
EXPECT(wc.acknowledge_level() == wc_level::k_default);
EXPECT(wc.timeout() == std::chrono::milliseconds(0));
}
{
wc.majority(std::chrono::milliseconds(5000));
db.write_concern(wc);
EXPECT(db.write_concern() == wc);
EXPECT(db.write_concern().acknowledge_level() == wc_level::k_majority);
EXPECT(db.write_concern().timeout() == std::chrono::seconds(5));
}
}
Collection Operations
Create a Collection
EXPECT(!db.has_collection("coll"));
EXPECT(coll);
EXPECT(db.has_collection("coll"));
}
Create a Collection With Options
EXPECT(!db.has_collection("coll"));
auto opts =
bsoncxx::from_json(R
"({"validationLevel": "strict", "validationAction": "error"})");
EXPECT(coll);
EXPECT(db.has_collection("coll"));
}
Query a Collection Exists
EXPECT(db.has_collection("present"));
EXPECT(!db.has_collection("missing"));
}
List Collections in the Database
int a = 0;
int b = 0;
int c = 0;
a = 0;
b = 0;
c = 0;
EXPECT(doc["name"]);
if (name == "a") {
++a;
} else if (name == "b") {
++b;
} else if (name == "c") {
++c;
}
}
};
{
count_fields(db.list_collections());
EXPECT(a == 1);
EXPECT(b == 1);
EXPECT(c == 0);
}
{
count_fields(db.list_collections(filter.view()));
EXPECT(a == 1);
EXPECT(b == 0);
EXPECT(c == 0);
}
}
List Collection Names in the Database
{
std::vector<std::string> names = db.list_collection_names();
EXPECT(std::count(names.begin(), names.end(), "a") == 1);
EXPECT(std::count(names.begin(), names.end(), "b") == 1);
EXPECT(std::count(names.begin(), names.end(), "c") == 0);
}
{
std::vector<std::string> names = db.list_collection_names(filter.view());
EXPECT(std::count(names.begin(), names.end(), "a") == 1);
EXPECT(std::count(names.begin(), names.end(), "b") == 0);
EXPECT(std::count(names.begin(), names.end(), "c") == 0);
}
}
Error Handling
Invalid Database
void example() {
try {
auto name = db.name();
EXPECT(false && "should not reach this point");
EXPECT(ex.code() == mongocxx::error_code::k_invalid_database_object);
}
}