2

I am creating an Index in Mongo using mongocxx with this code:

auto index_specification = bsoncxx::builder::stream::document{} << "_tablename" << 1 << "rowuuid" << 1 << bsoncxx::builder::stream::finalize;
auto result = coll.create_index(std::move(index_specification));

However, I don't know how to check if it was successful. I tried to print out the result with:

printf((const char*) result.view().data());

But I just get a & character. I have been looking over the internet but I cannot find an answer.

Cœur
  • 37,241
  • 25
  • 195
  • 267
QLands
  • 2,424
  • 5
  • 30
  • 50
  • 1
    Because the result isn't text, its BSON. Try calling `bsoncxx::to_json` on the result, and printing that out. That should give you an idea what fields in the returned document you should examine to determine the outcome. – acm Jan 03 '18 at 01:02

1 Answers1

2

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!

JTejedor
  • 1,082
  • 10
  • 24