如何使用 mongo-cxx-driver 的 **insert** 函数将包含静态数据的多维数组插入到数据库中

How to inserta nd retreive Multidimension array with static data in it into database using **insert** function of mongo-cxx-driver?

本文关键字:数组 插入 数据库 数据 包含 mongo-cxx-driver 何使用 insert 函数 静态      更新时间:2023-10-16

我尝试了将数组传递给包装器函数的传统方法,在该函数中,我使用 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;
}
}

几乎可以肯定,collection.insert_one(doc.view()); 中抛出了异常。您应该捕获该异常(通过使用 trycatch ),并检查异常的内容,这应该会告诉您有关出错的更多信息。