Search code examples
c++mongodbbsonmongo-cxx-driver

How to write a bsoncxx::document::element to the console


I have the following function that gets a value out of a BSON document when given a sequence of keys:

bsoncxx::document::element deepFieldAccess(bsoncxx::document::view bsonObj, const std::vector<std::string>& path) {

    if (path.empty())
        return {};

    auto keysIter = path.begin();
    const auto keysEnd = path.end();

    auto currElement = bsonObj[*(keysIter++)];
    while (currElement && (keysIter != keysEnd))
        currElement = currElement[*(keysIter++)];

    return currElement;
}

The returned bsoncxx::document::element can hold a value of any type (int32, document, array, utf8, etc). How can I write this element to the console via std::cout?

Ideally, I would just have to do:

bsoncxx::document::element myElement = deepFieldAccess(bsonObjView, currQuery);
std::cout << myElement << std::endl;

Solution

  • We can't print bsoncxx::document::element, but we can print bsoncxx::document::view. So just convert one into the other and clean up the resulting string. It's ugly and inefficient but works for quickly looking up the value of a bsoncxx::document::element.

    std::string turnQueryResultIntoString(bsoncxx::document::element queryResult) {
    
        // check if no result for this query was found
        if (!queryResult) {
            return "[NO QUERY RESULT]";
        }
    
        // hax
        bsoncxx::builder::basic::document basic_builder{};
        basic_builder.append(bsoncxx::builder::basic::kvp("Your Query Result is the following value ", queryResult.get_value()));
    
        // clean up resulting string
        std::string rawResult = bsoncxx::to_json(basic_builder.view());
        std::string frontPartRemoved = rawResult.substr(rawResult.find(":") + 2);
        std::string backPartRemoved = frontPartRemoved.substr(0, frontPartRemoved.size() - 2);
    
        return backPartRemoved;
    }