gpt4 book ai didi

c++ - 如何将 bsoncxx::document::element 写入控制台

转载 作者:太空宇宙 更新时间:2023-11-04 12:29:50 24 4
gpt4 key购买 nike

我有 following function在给定键序列时从 BSON 文档中获取值:

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;
}

返回的bsoncxx::document::element可以包含任何类型的值(int32documentarrayutf8 等)。如何通过 std::cout 将此元素写入控制台?

理想情况下,我只需要做:

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

最佳答案

我们不能打印bsoncxx::document::element,但是我们可以打印bsoncxx::document::view。因此,只需将一个转换为另一个并清理生成的字符串。它既丑陋又低效,但可以快速查找 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;
}

关于c++ - 如何将 bsoncxx::document::element 写入控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59116086/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com