2

我的程序可能连接很少,我需要关闭每个连接。请帮帮我。

#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() 或者我该如何关闭它?

4

1 回答 1

5

mongocxx::client不提供显式断开或关闭方法,因为它实际上是另一个内部私有客户端类的包装器,该类具有终止连接的析构函数。

如果您查看mongocxx::client声明,它包含一个成员std::unique_ptr<impl> _impl

这是一个指向实例的唯一指针,该实例mongocxx::client::impl实现了一个析构函数,libmongoc::client_destroy(client_t);当您的客户端对象被销毁时调用该析构函数。

如果您的应用程序要多次连接/重新连接,您可能有兴趣使用mongocxx::Pool,它管理与 MongoDB 实例的多个连接,然后您可以在必要时从中获取连接。mongocxx如果您在多线程应用程序中,这也是推荐的使用方式,因为该标准mongocxx:client不是线程安全的。

于 2016-12-20T20:31:20.830 回答