Search code examples
mongodbc++11bsonmongo-cxx-driver

mongo-cxx-driver doubles to json


While experimenting with the C++11 driver of MongoDB (version 3.1.0-rc0) the output of the following piece of code confused me.

#include <iostream>

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>

int main() {
  bsoncxx::builder::stream::document s;
  s << "x" << 1.0;

  std::cout << bsoncxx::to_json(s) << std::endl;

  return 0;
}

Output:

{ "x" : 1 }
  1. Is this the expected behavior?
  2. How can I make sure that BSON doubles are represented as floating point numbers in JSON?

Configuration: CentOS 7, gcc 6.2.0, mongo-c-driver 1.5.0, mongo-cxx-driver 3.1.0-rc0


Solution

  • It looks like that behavior is inherent to libbson, which provides the JSON serialization. It's sort of technically correct, since Javascript doesn't distinguish numeric types, but I understand how you'd prefer it to keep the decimal component, even if 0.

    So at the moment, the answer to your questions are

    1. Not expected, but not surprising.
    2. At the moment, you can't do that from mongocxx. You could iterate the BSON structure and construct a JSON document with another JSON library.

    I'll take up the issue with the libbson maintainers as well. (Update: Filed ticket CDRIVER-1945).