How do you to convert a bson_t (older bson c type) to a bsoncxx::document?

77 Views Asked by At

So far I've thought about using an iterator to manually fetch each field of the bson_t, something like this:

bsoncxx::builder::stream::document view_builder;
bson_iter_t iter;
bson_iter_init(&iter, &bson_t_doc);

while (bson_iter_next(&iter)) {
    const char* key = bson_iter_key(&iter);
    bson_type_t type = bson_iter_type(&iter);

    switch (type) {
        case BSON_TYPE_UTF8:
            view_builder << key << bsoncxx::types::b_utf8{bson_iter_utf8(&iter, nullptr)};
            break;
        case BSON_TYPE_INT32:
            view_builder << key << bsoncxx::types::b_int32{bson_iter_int32(&iter)};
            break;
        case BSON_TYPE_INT64:
            view_builder << key << bsoncxx::types::b_int64{bson_iter_int64(&iter)};
            break;
        default:
            break;
    }
}

However this approach would need a pretty big and ugly switch with all supported types (granted for my use I could isolate only the ones used in the old bson_t documents...)

I have been trying to find an actual function for this but it seems that there isn't one. As a note, the bson_t type does not seem to expose the binary buffer at all so it seems I can't quickly access the binary data.

Has anyone done something similar?

1

There are 1 best solutions below

2
On

"If I were to include libbson I could simply use bson_get_data()..." why not do so?

The bson_get_data() function shall return the raw buffer of a bson document. This can be used in conjunction with the len property of a bson_t if you want to copy the raw buffer around.

bson_t::bson_get_data()

With the raw binary data and length, use these to instantiate a bsoncxx::document::view.

This is more efficient than copying the binary data (could be 16mb in size) from the bson_t instance to a bsoncxx::document::view using bsoncxx::builder::stream::document like you did in your example.