Search code examples
c++mongodbmongo-cxx-driver

How to use insert_many() method of MongoDB in C++?


I am using a method to store some data in a MongoDB database.

void save_data(std::vector< class_a > list){
    using namespace std;
    using bsoncxx::builder::stream::document;
    using bsoncxx::builder::stream::finalize;

    std::vector< bsoncxx::document::value > documents;
    for (size_t i = 0; i < list.size(); i++){
        documents.push_back(document{}
            << "field 1" << list[i].get_data_1()
            << "field 2" << list[i].get_data_2()
            << finalize);
    }

    collection.insert_many(documents);
}

I know the list has stored more than 1 object of class_a. I used the method name() of the mongocxx::collection object collection to test if it is accessable. It returned its name as expected. So there is a client set, I think. But the insert_many() method throws an error:

"mongoc_bulk_operation_execute() requires a client and one has not been set.: generic server error"

What am I doing wrong?


Solution

  • I see, the function acquire() from the pointer std::unique_ptr _pool returns the client.