I’m attempting to build a document that looks like this:
{
"Name" : "Joe",
"Age" : 34,
"Some Array" : [
{ "index" : 1, "Some Var" : 12, "Flag" : false },
{ "index" : 2, "Some Var" : 13, "Flag" : true },
{ "index" : 3, "Some Var" : 14, "Flag" : false }
],
"Status" : "Employed"
}
and I’ve been somewhat successful using the streaming builders as long as I do it all in one shot like this:
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::open_document;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::open_array;
using bsoncxx::builder::stream::close_array;
using bsoncxx::builder::stream::finalize;
bsoncxx::builder::stream::document ArrayDoc;
ArrayDoc << "Name" << "Joe"
<< "Age" << 34
<< "Some Array" << open_array << open_document
<< "index" << 1 << "Some Var" << 12 << "Flag" << false
<< close_document << open_document
<< "index" << 2 << "Some Var" << 13 << "Flag" << true
<< close_document << open_document
<< "index" << 3 << "Some Var" << 14 << "Flag" << false
<< close_document
<< close_array
<< "Status" << "Employed";
What I really need to do though, is build the subarray with a loop to fetch the various values from other data structures. When I try to break the building process into parts, I get compiler errors on the open_document
bsoncxx::builder::stream::document ArrayDoc;
ArrayDoc << "Name" << "Joe"
<< "Age" << 34
<< "Some Array" << open_array;
for (int i = 0; i < 4; i++)
{
ArrayDoc << open_document
<< "index" << i << "Some Var" << 12 << "Flag" << false
<< close_document;
}
ArrayDoc << close_array
<< "Status" << "Employed";
The above gets me:
error C2679: binary '<<': no operator found which takes a right-hand operand of type 'const bsoncxx::v_noabi::builder::stream::open_document_type' (or there is no acceptable conversion)
What am I doing wrong?
2
Answers
Instead of using the document stream builder, I suggest using the basic builder so you can create the different parts of the document as needed. In your case, you have several key/value pairs and an embedded array of value lists. The change in your thinking is to create subdocuments and use those to build the overall document.
So if you have a two-dimensional array of data that will be presented as an array in your (final) document:
then you should build this array as it’s own (intermediate) document
Now you can use
some_array
as a subdocument in the overall document.Here is a self-contained example that runs for me:
This gives the output
The error you got seems linked to the following (it contains a neat example):
https://github.com/mongodb/mongo-cxx-driver/blob/a6ee87e2ff23965eaddb2dc3bfc6d1e84c52a98d/docs/content/mongocxx-v3/working-with-bson.md#L135
So one way to achieve this would be: