Recently I have found myself in the same problem. To know if a create_index
operation was succesful, you should expect no exception thrown and check if exists a key with "name" in the returned document::value
. A full example to know how to check for a successful create_index operation is below (extracted mostly from tests related to collection in src/mongocxx/tests/collection.cpp
):
bool success = false;
try {
mongocxx::client a {
mongocxx::uri {
"mongodb://localhost:27017"
}
};
mongocxx::database database = a.database("test");
mongocxx::collection collection = database["test-collection"];
collection.drop();
collection.insert_one({}); // Ensure that the collection exists.
bsoncxx::document::value index = bsoncxx::builder::stream::document {} << "a" << 1 << bsoncxx::builder::stream::finalize;
std::string indexName {
"myName"
};
mongocxx::options::index options {};
options.name(indexName);
bsoncxx::document::value result = collection.create_index(index.view(), options);
bsoncxx::document::view view = result.view();
if (not view.empty() && view.find("name") != view.end()) {
success = true;
std::cout << bsoncxx::to_json(view) << std::endl;
}
} catch (mongocxx::exception e) {
std::cerr << e.what() << ":" << e.code().value() << std::endl;
}
Sorry for this very late answer but I have found just today, searching for other topic related with mongo-driver-cxx.
I hope it still works for you!