Search code examples
mongo-cxx-driver

Create bsoncxx::builder::basic::document from a string?


Is there a way to create a bsoncxx::builder::basic::document from a std::string?

I know how to build a document using mongocxx functions such as make_document, kvp, make_array, as well as through the streaming functions.

But what I want to know is if we can create a std::string representation of a document and make that into a bsoncxx::builder::basic::document?


Solution

  • Assuming that this std::string contains JSON, then yes. You can invoke bsoncxx::from_json.

    If, somehow, the std::string buffer contains BSON data rather than JSON, you could copy the data inside the string into a new buffer and use one of the first two bsoncxx::document::value::value constructors, which take ownership of a buffer.

    You could also construct a temporary bsoncxx::document::view over the buffer in the std::string by passing the underlying .data() and .length() of the string to the two argument bsoncxx::view::view constructor, and then pass that view along to the appropriate bsoncxx::value constructor, which will copy the data in the view.