MongoCxx 3.1.0 How can I close connection?

1.6k Views Asked by At

I have program which may have few connections and I need close each one connections. Help me please.

#include <iostream>

#include <bsoncxx/builder/stream/document.hpp>
#include <bsoncxx/json.hpp>

#include <mongocxx/client.hpp>
#include <mongocxx/instance.hpp>

int main(int, char**) {
    mongocxx::instance inst{};
    mongocxx::client conn{mongocxx::uri{}};

    bsoncxx::builder::stream::document document{};

    auto collection = conn["testdb"]["testcollection"];
    document << "hello" << "world";

    collection.insert_one(document.view());
    auto cursor = collection.find({});

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

}

conn.close() or how can I close it?

1

There are 1 best solutions below

0
On

mongocxx::client doesn't provide an explicit disconnect or close method because it is actually a wrapper around another internal, private client class that has a destructor that terminates the connection.

If you look at the mongocxx::client declaration, it contains a member std::unique_ptr<impl> _impl.

This is a unique pointer to an instance of mongocxx::client::impl which implements a destructor that calls libmongoc::client_destroy(client_t); when your client object is destroyed.

If your application is going to be connecting/reconnecting many times, you might be interested in using mongocxx::Pool, which manages a number of connections to a MongoDB instance, and then you can obtain a connection from it when necessary. It's also the recommended way to use mongocxx if you're in a multithreaded application, as the standard mongocxx:client is not thread-safe.