Is it possible to serialize bsoncxx::document to a binary file

Hello,

I am new to mongodb. I have started working with mongodb c++ driver. I was wondering is it possible to serialize bsoncxx::document to a binary file and also create bsoncxx::document from a binary file ?

Regards

@Ahsan_Iqbal

Yes, I used to do this a lot back when I worked with a lot of IoT devices and services.

It is possible to serialize bsoncxx::document to a binary file and create bsoncxx::document from a binary file using the MongoDB C++ driver.

To serialize a bsoncxx::document to a binary file, you can use the bsoncxx::to_json function to convert the document to a JSON string, and then write the string to a file using standard file I/O functions. For example:

bsoncxx::document::view view = ...; // your document view
std::string json_str = bsoncxx::to_json(view);
std::ofstream ofs("document.bin", std::ios::binary);
ofs.write(json_str.c_str(), json_str.size());

To create a bsoncxx::document from a binary file, you can read the JSON string from the file using standard file I/O functions, and then use the bsoncxx::from_json function to parse the JSON string and create a new document. For example:

std::ifstream ifs("document.bin", std::ios::binary);
ifs.seekg(0, std::ios::end);
size_t size = ifs.tellg();
ifs.seekg(0, std::ios::beg);
std::string json_str(size, '\0');
ifs.read(&json_str[0], size);
bsoncxx::document::value value = bsoncxx::from_json(json_str);
bsoncxx::document doc(value.view());

Note: This approach will work only if the BSON document is valid JSON. If the document contains binary data or other non-JSON data types, you may need to use a different serialization format, such as BSON, instead of JSON.

Here’s an article that covers this topic - Storing Binary Data with MongoDB and C++ | MongoDB

1 Like