Mongodb c++驱动程序3.0,而不是const数组

Mongodb c++ driver 3.0, not const arrays

本文关键字:const 数组 c++ 驱动程序 Mongodb      更新时间:2023-10-16

我正在尝试创建一个包含向量内容的数组

using bsoncxx::builder::stream;
auto doc = document{};
doc << "foo"
  << open_array;
for (auto i : v){
  doc << open_document << "bar" << i << close_document ;
}
doc << close_array;

我收到以下错误报告:

error: no match for ‘operator<<’ (operand types are ‘bsoncxx::v0::builder::stream::document’ and ‘const bsoncxx::v0::builder::stream::open_document_type’)
       doc << open_document << "bar" << i << close_document ;

你知道怎么做吗?

C++11 bson驱动程序实际上在流式api下隐藏了比最初出现的更复杂的东西。

您遇到的问题是,在每个连续的'<lt;',所以从你最初的例子来看,你需要:

auto sz = 100;
// Note that we capture the return value of open_array
auto arr = doc << "foo" << open_array;
for (int32_t i=0; i < sz; i++)
    arr << i;
arr << close_array;

这是因为open_array创建了一个嵌套类型,可以接受没有键的值,而不像doc那样需要键值对。

如果你想要更内联的东西,你可以使用内联可调用功能,如:

auto sz = 100;
builder::stream::document doc;
doc << "foo" << open_array <<
    [&](array_context<> arr){
        for (int32_t i = 0; i < sz; i++)
            arr << i;
    } // Note that we don't invoke the lambda
<< close_array;

可调用的设施与需要的东西一起工作:

single_context-在数组中写入一个值,或作为键值对的值部分

key_context<>-写入任意数量的键值对

array_context<>-写入任意数量的值

有关的更多示例,请参见src/bsoncxx/test/bsn_builder.cpp

我对流构建器也有同样的问题。

using bsoncxx::builder::stream;
auto doc = document{};
doc << "foo"
    << open_array
    << open_document
    << "bar1" << 1 
    << "bar2" << 5
    << close_document
    << close_array;

上面的工作,然而,如果你想做以下事情,它不工作

doc << "foo"
    << open_array;
for (size_t i=0; i < sz; i++)
    doc << i;
doc << close_array;

我得到以下错误。问题是,这种行为使得使用流生成器实际上毫无用处。也许这是一个bug,或者10代人还并没有完成API的这一部分。

doc << closerror: no match for ‘operator<<’ (operand types are ‘bsoncxx::v0::builder::stream::document’ and ‘const bsoncxx::v0::builder::stream::open_document_type’) doc << open_document << "bar" << i << close_document ;e_array;