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?
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 memberstd::unique_ptr<impl> _impl
.This is a unique pointer to an instance of
mongocxx::client::impl
which implements a destructor that callslibmongoc::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 usemongocxx
if you're in a multithreaded application, as the standardmongocxx:client
is not thread-safe.