如何使用mongo-cxx-driver驱动程序的“插入”功能将包含静态数据的可逆多维数组插入数据库?

时间:2019-01-29 11:20:26

标签: c++ mongodb visual-studio mongo-cxx-driver

我尝试了将数组传递给包装函数的常规方法,其中使用 insertOne 使用for循环插入数据。没有任何构建问题,但是在运行时,我遇到了以下错误:Microsoft C ++异常:内存位置0x000000B26C12DF30的mongocxx :: v_noabi :: bulk_write_exception。这是我的源代码

int main(void) {

char EUI[][20] = { "10205E3710014240", "10205e37100142cc" ,"10205E6910001E58", "10205E371001426C" };
char IP[][15] = { "192.168.85.117" , "192.168.85.114", "192.168.85.186",  "192.168.85.168" };
int i = 4;

push_data(IP, EUI, i);
while (1);
}

void push_data(char IP[][15], char EUI[][20], int count)
{
mongocxx::instance inst{};
mongocxx::client conn{ mongocxx::uri{} };
auto collection = conn["new"]["collection"];

int a;
builder::stream::document builder{};

auto in_array = builder << "subdocs" << builder::stream::open_array;
for (a = 0; a<count; a++) {
        in_array = in_array << builder::stream::open_document << EUI[a] << IP[a]
            << builder::stream::close_document;
}
auto after_array = in_array << builder::stream::close_array;
bsoncxx::document::value doc = after_array << builder::stream::finalize;

bsoncxx::document::view view = doc.view();
for (a = 0; a < count; a++) {
    collection.insert_one(doc.view());
}

auto cursor = collection.find({});

for (auto&& doc : cursor) {
std::cout << bsoncxx::to_json(doc) << std::endl;
}
}

1 个答案:

答案 0 :(得分:0)

几乎可以肯定,已经从collection.insert_one(doc.view());引发了异常。您应该捕获该异常(通过使用trycatch),并检查异常的内容,这应该告诉您更多有关出了什么问题的信息。