Search code examples
c++mongodbboostdriverboost-propertytree

How to insert a Boost ptree into MongoDB using C++


I have MongoDB C++ Driver at https://mongodb.github.io/mongo-cxx-driver/mongocxx-v3/tutorial/ compiled and ready, tested OK with literal data.

But the challenge is how to store a Boost ptree into MongoDB as a document. I have a Boost ptree because I'm using Boost to parse JSON string.

The process is as following:

Input --> JSON String (OK) --> Boost ptree (OK) --> MongoDB insert (stuck!)


Solution

  • Got a solution finally!

    These are the steps:

    • ptree can be obtained from parsing JSON string (Boost read_json)
    • Check or modify values in ptree object
    • Convert the ptree back to JSON string using Boost write_json
    • Convert to MongoDB BSON value: bsoncxx::document::value Doc = bsoncxx::from_json(Str)
    • Insert to DB: cxxClient["dbname"]["collection"].insert_one(Doc.view());