Building a document out of json in C++

Hello, I am trying to build up a dcument in C++ out of json file, here is my json:

{
    "Id": "myId",
    "Sys": "mySys",
    "Components": [
        {
            "Name": "myName",
            "Parts": [
                {
                    "Id": "myId1",
                    "Name": "myName1"
                },
                {
                    "Id": "myId2",
                    "Name": "myName2"
                }
            ]
        }
    ]
}

and here is my C++ code to build such a document:

for (auto& config : Configs) {
  bsoncxx::builder::stream::document doc_builder{};

  auto doc1 = doc_builder << "Id" << config.Id
    << "Sys" << config.Sys
    << "Components" << bsoncxx::builder::stream::open_array;
  for (auto& comp: config.Components) {
    doc1 = doc1 << bsoncxx::builder::stream::open_document
      << "Name" << comp.Name;
    auto doc2 = doc1 << "Parts" << bsoncxx::builder::stream::open_array;
    for (auto& part: comp.Parts) {
      doc2 = doc2 << bsoncxx::builder::stream::open_document
        << "Id" << part.Id
        << "Name" << part.Name
        << bsoncxx::builder::stream::close_document;
    }
    auto doc4 = doc2 << bsoncxx::builder::stream::close_array
      << bsoncxx::builder::stream::close_document;
    doc1 = doc1 << doc4;
  }
  auto                     doc5 = doc1 << bsoncxx::builder::stream::close_array;
  bsoncxx::document::value doc  = doc5 << bsoncxx::builder::stream::finalize;
// here i save doc5;
}

i appreciate your help, thanks.

Mouaz,

Hi @muaz_sh

Not sure what the question is, but in case you’re trying to create a BSON document out of a JSON file, you could use the from_json function.

https://mongocxx.org/api/current/namespacebsoncxx_1_1v__noabi.html#ab0e7628a9514418eee8fbb66a1ec20f6

Hi @Rishabh_Bisht,

Thanks for replying, the thing is that c++ code is not compilable, for that i followed the example you provided here https://www.mongodb.com/docs/languages/cpp/drivers/current/working-with-bson/ with operator <<, when i change this doc1 = doc1 << doc4; to doc1 = doc4; it compiles, however, since i am new dealing with MongoDB i guess from_json will do the job.