c++mongodbmongo-cxx-driver

bsoncxx - is there a way to iterate through documents in .bson dump file?


Similarly to how we construct bsoncxx::document::view objects from a buffer with a single binary document, is there a way to extract single documents from a collection in a .bson dump in this framework without having to load them into a DB?

i.e. what works for single document objects

uint8 *buffer; // single bson document
size_t length; // size of buffer
bsoncxx::document::view view(buffer, length);

for (auto elem : view) {
doSomethingWithElem()
}

I'd like to be able to construct a cursor for the whole dump, but without loading it into a collection. Is something like this possible?


Solution

  • Found the solution and it was pretty simple in the end - I utilized the libbson library. An example of what I used below:

    #include <bson.h>
    // and other includes
    
    void read_bson() {
    
        bson_reader_t *reader;
        const bson_t *doc;
        bson_error_t error;
        bool eof;
        char *path;
    
        reader = bson_reader_new_from_file(path, &error);
    
    if (reader)
            {
                while ((doc = bson_reader_read(reader, &eof)))
                {
                      const uint8_t *buffer = bson_get_data(doc);
                      auto view = bsoncxx::document::view(buffer, doc->len);
                 }
             }
    }