MongoDB c++ Driver 3.0获取字符串文档,避免json

MongoDB C++ Driver 3.0 get document in string and avoid json

本文关键字:文档 避免 json 字符串 获取 c++ Driver MongoDB      更新时间:2023-10-16

我正试图从数据库中获得双类型数据,如文档所说:

auto cursor = db["collection"].find({}, opts);
for (auto&& doc : cursor) {
    std::cout << bsoncxx::to_json(doc) << std::endl;
}

但是我想避免将doc转换为json,因为我失去了十进制精度。例如:

In database显示如下:

"lng" : -58.4682568037741

但转换为json后,我收到这个:

"lng" : -58.4682

是否有办法直接转换成字符串,例如?

您可以将您想要的字段直接拉出为双精度类型。要打印高精度输出,需要在输出流上设置它。例如

for (auto&& doc : cursor) {
    std::cout << std::setprecision(15)
              << "lng: " << doc["lng"].get_double() << std::endl;
}

给:

lng: -58.4682568037741

在调用get_double之前,您可能需要验证doc["lng"]是BSON双精度对象。