2

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!)

Dee
  • 7,455
  • 6
  • 36
  • 70
  • http://stackoverflow.com/users/776473/acm – Dee Nov 22 '16 at 09:23
  • `Input --> JSON String (OK) --> MongoDB insert (OK)` -- FTFY – sehe Nov 22 '16 at 09:25
  • (Hint: you should have a reason to transform the data. Without that reason, Boost Property Tree is useless. My gut says that when you describe the goal, it will be clear that Boost Property Tree is not the right tool for the job). – sehe Nov 22 '16 at 09:30
  • i need to convert to ptree to check some values – Dee Nov 22 '16 at 09:32
  • i tried to use bsoncxx::from_json instead of ptree parser, but this error is shown when inserting: src/mongoc/mongoc-topology.c:481 mongoc_topology_select(): precondition failed: topology – Dee Nov 22 '16 at 10:08
  • And how does using `ptree` help? Because Boost doesn't have a JSON library. It would be better to root-cause that error message instead of hoping that using PropertyTree will magically remove the problem. My experience is that using PropertyTree for anything other than property-trees (e.g. abuse it for general XML or JSON support) is a non-flyer – sehe Nov 22 '16 at 10:18
  • 1
    crap, my error, not mongo, client closed – Dee Nov 22 '16 at 10:18
  • fine, i'm trying to use bsoncxx instead – Dee Nov 22 '16 at 10:18

1 Answers1

1

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());
Dee
  • 7,455
  • 6
  • 36
  • 70