选择连接目标
概述
在本指南中,您可以了解如何使用连接字符串和mongocxx::client
对象连接到不同类型的MongoDB部署。
Atlas
要连接到Atlas上的MongoDB部署,请在您的连接字符串中包含以下元素
Atlas集群的URI
MongoDB用户名
MongoDB密码
然后,将您的连接字符串传递给mongocxx::uri
构造函数,并使用mongocxx::uri
对象构建一个mongocxx::client
对象。
当您连接到Atlas时,我们建议使用稳定API客户端选项,以避免Atlas升级到MongoDB服务器的新版本时发生破坏性更改。有关稳定API功能的更多信息,请参阅稳定API页面.
以下代码展示了如何使用C++驱动程序连接到Atlas集群。代码还使用server_api_opts
选项指定稳定API版本。
using bsoncxx::builder::basic::kvp; using bsoncxx::builder::basic::make_document; int main() { mongocxx::instance instance; // Replace the placeholder with your Atlas connection string mongocxx::uri uri("<connection string>"); // Create a mongocxx::client with a mongocxx::options::client object to set the Stable API version mongocxx::options::client client_options; mongocxx::options::server_api server_api_options(mongocxx::options::server_api::version::k_version_1); client_options.server_api_opts(server_api_options); mongocxx::client client(uri, client_options); try { // Ping the server to verify that the connection works auto admin = client["admin"]; auto command = make_document(kvp("ping", 1)); auto result = admin.run_command(command.view()); std::cout << bsoncxx::to_json(result) << "\n"; std::cout << "Pinged your deployment. You successfully connected to MongoDB!\n"; } catch (const mongocxx::exception &e) { std::cerr << "An exception occurred: " << e.what() << "\n"; return EXIT_FAILURE; } }
提示
遵循Atlas驱动程序连接指南以获取您的连接字符串。
本地部署
要连接到本地MongoDB部署,请使用localhost
作为主机名。默认情况下,mongod
进程在端口27017上运行,但您可以自定义您的部署。
以下代码演示了如何使用C++驱动程序连接到本地MongoDB部署
int main() { mongocxx::instance instance; mongocxx::uri uri("mongodb://localhost:27017"); mongocxx::client client(uri); }
副本集
要连接到副本集,请在连接字符串中指定副本集成员的主机名(或IP地址)和端口号。
如果您无法提供副本集的完整主机列表,您可以指定一个或多个副本集主机,并指示C++驱动程序进行自动发现以找到其他主机。要指示驱动程序执行自动发现,请执行以下操作之一
将副本集的名称指定为
replicaSet
参数的值。将
directConnection
参数的值指定为false
。指定副本集中的多个主机。
在以下示例中,驱动程序使用示例连接URI连接到MongoDB副本集sampleRS
,该副本集运行在三个不同主机(包括host1
)的端口27017
上。
int main() { mongocxx::instance instance; mongocxx::uri uri("mongodb://host1:27017/?replicaSet=sampleRS"); mongocxx::client client(uri); }
初始化
要初始化副本集,您必须直接连接到单个成员。为此,在连接字符串中将directConnection
连接选项设置为true
。以下代码示例显示了如何设置此连接选项
int main() { mongocxx::instance instance; mongocxx::uri uri("mongodb://<hostname>:<port>/?directConnection=true"); mongocxx::client client(uri); }
API 文档
要了解更多关于本页使用的类型,请参阅以下API文档