0

When adding an array to document, open_array and close_array must come at the same time when throwing into the document stream. The follow code fails (compile time) at the last line when adding 'close_array'.

vector<string> List;
...

document Doc;
Doc <<"List" <<open_array;
for (string Str: List) {
  Doc <<Str;
}
Doc <<close_array;

But I don't know the number of elements in the 'List' to add to document at the same time. MongoDB still lacks examples for the C++ driver.

This code works but the number of items in the 'List' is not known.

Doc 
<<open_array
<<List[0] <<List[1] <<List[2] <<...
<<close_array;

G++ error:

content.cpp:65:7: error: no match for ‘operator<<’ (operand types are ‘bsoncxx::v_noabi::builder::stream::document’ and ‘const bsoncxx::v_noabi::builder::stream::close_array_type’)
   Doc <<close_array;
   ~~~~^~~~~~~~~~~~~
compilation terminated due to -Wfatal-errors.
Community
  • 1
  • 1
Dee
  • 7,455
  • 6
  • 36
  • 70

1 Answers1

0

Found a solution from Adding a BSON Array to a MongoDB 3.2 document and extracting the values back ( MongoCXX 3.2 ) ( C++ 11)

It's not able to add the 'close_array' to the document itself, it must be added thru' an array builder (type 'auto', I didn't dig it out to find the real type).

auto Array = Doc <<"List" <<open_array;
for (string Str: List) 
  Array <<Str;
Array <<close_array;

To be noted that the above code works fine, but the following won't

auto Array = Doc <<"List";
Array <<open_array;
for (string Str: List) 
  Array <<Str;
Array <<close_array;
Community
  • 1
  • 1
Dee
  • 7,455
  • 6
  • 36
  • 70