Skip to content

Latest commit

 

History

History
56 lines (43 loc) · 1.79 KB

20170711.md

File metadata and controls

56 lines (43 loc) · 1.79 KB

How to: create a document using kvp, get value from document and print it in json format

// g++ app1.cpp -std=c++14 -I/usr/include/bsoncxx/v_noabi -I/usr/include/libbson-1.0 -lbsoncxx

#include <bsoncxx/json.hpp>
#include <bsoncxx/builder/basic/array.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <bsoncxx/types.hpp>
#include <iostream>

int main (int, char**)
{
  auto doc = bsoncxx::builder::basic::document{};
  doc.append(bsoncxx::builder::basic::kvp("string", "value"));
  doc.append(
    bsoncxx::builder::basic::kvp("bool", bsoncxx::types::b_bool{true}));
  doc.append(
    bsoncxx::builder::basic::kvp("double", bsoncxx::types::b_double{3.14}));

  doc.append(bsoncxx::builder::basic::kvp(
      "subdocument", [](bsoncxx::builder::basic::sub_document subdoc)
      {
        subdoc.append(bsoncxx::builder::basic::kvp("subdoc_string", "value"),
          bsoncxx::builder::basic::kvp(
            "subdoc_int64", bsoncxx::types::b_int64{1212}));
      }));

  doc.append(bsoncxx::builder::basic::kvp(
      "subarray", [](bsoncxx::builder::basic::sub_array subarr)
      {
        subarr.append("aloha", 42, bsoncxx::types::b_bool{true},
            [](bsoncxx::builder::basic::sub_document subdoc) {
              subdoc.append(bsoncxx::builder::basic::kvp("any", "value"));
            });
      }));

  auto v = doc.view();

  auto docElem = v["bool"];
  std::cout << "value: " << docElem.get_bool() << std::endl;

  docElem = v["subdocument"]["subdoc_int64"];
  std::cout << "subdocument: " << docElem.get_int64() << std::endl;

  auto arrElem = v["subarray"][1];
  std::cout << "subarray: " << arrElem.get_int32() << std::endl;

  std::cout << bsoncxx::to_json(v) << std::endl;
}