Is there a bson_new_from_data equivalent for bsoncxx (c++ driver)?

Hello there. First time posting, please be gentle.

I’ve been tasked with lifting lots of code from libmongoc to mongocxx. A lot of things I can do manually and have helped me to learn the driver better, but I ran into something which I do not quite have a fix for.

Within a function populating a new mongodb document, a function called “bson_new_from_data” is used to create a new subdocument and appending it. I have tried searching for an equal function in mongocxx/bsoncxx but to no avail. The suggestions I have so far:

        << "some_field_name"
        << bsoncxx::types::b_binary{
            reinterpret_cast<const uint8_t*>(data_pointer)
  • same as above but different syntax;
<< "some_field" 
<<  bsoncxx::types::b_binary{
bsoncxx::binary_sub_type::k_binary, data_size, (const uint8_t*)&data_pointer

Will either of these work to replace the (much more elegant) bson_new_from_data function? Is there a difference in a binary that is bson and bsoncxx?

Hi @lnorth

Welcome to the MongoDB community!

You should be able to achieve the desired outcome with the first option, ie. by creating a bsoncxx::document::view from the data and appending.

#include <mongocxx/instance.hpp>
#include <bsoncxx/builder/basic/kvp.hpp>
#include <bsoncxx/builder/basic/document.hpp>
#include <bsoncxx/json.hpp>

#include <cstdlib>
#include <iostream>

using namespace bsoncxx::builder::basic;
int main()
    auto instance = mongocxx::instance();

    // `bsondata` represents the document { "foo" : "bar" }
    uint8_t bsondata[] = {
        0x12, 0x00, 0x00, 0x00, 0x02, 0x66, 0x6f, 0x6f, 0x00, 0x04, 0x00, 0x00, 0x00, 0x62, 0x61, 0x72, 0x00, 0x00};
    auto doc = bsoncxx::document::view(bsondata, sizeof bsondata);
    // Append as a subdocument:
    auto doc2 = make_document(kvp("subdoc", doc));
    std::cout << bsoncxx::to_json(doc2) << std::endl;
    // Prints `{ "subdoc" : { "foo" : "bar" } }`.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.