Search code examples
mongo-cxx-driver

Iterate through a mongocxx query to get each key and value


I am querying a collection with the following code:

bsoncxx::stdx::optional<bsoncxx::document::value> query_result =
collection.find_one(bsoncxx::builder::stream::document{} << "_tablename" << tableToSearch.toUtf8().constData() << "rowuuid" << UUIDToSearch.toUtf8().constData() << bsoncxx::builder::stream::finalize);
if(query_result)
{

}

I can see from the documentation how to print the result:

std::cout << bsoncxx::to_json(*maybe_result) << "\n";

But how can I Iterate through the result to get each key and its value as string?


Solution

  • Please have a read through the mongocxx and bsoncxx examples. You can find the example demonstrating cursor iteration here:

    https://github.com/mongodb/mongo-cxx-driver/blob/fc9a44325e03bb8bb166e814caeb23413b4ba7af/examples/mongocxx/query.cpp#L43-L46

    However, in your example you are doing a find one, so I guess you want to iterate each field, not each document. In that case, you can see examples of walking BSON objects here:

    https://github.com/mongodb/mongo-cxx-driver/blob/fc9a44325e03bb8bb166e814caeb23413b4ba7af/examples/bsoncxx/view_and_value.cpp#L61-L62