简体   繁体   中英

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

I am trying to get double type data from the database as the documentation says:

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

But I want to avoid converting doc into json because I lost decimal precision. For example:

In database shows this:

"lng" : -58.4682568037741

But after converting to json, I receive this:

"lng" : -58.4682

Is there any way to convert it directly to string, for example?

You can pull out the field you want directly as a double. To print high-precision output, you need to set that on the output stream. Eg

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

Gives:

lng: -58.4682568037741

You may want to verify that doc["lng"] is a BSON double before calling get_double .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM