创建 MongoClient
概述
要连接到MongoDB部署,您需要以下两样东西
一个连接URI,也称为连接字符串,它告诉C驱动程序连接到哪个MongoDB部署。
一个
mongoc_client_t
结构,它创建与MongoDB部署的连接并执行操作。
本指南展示了如何创建连接字符串,并使用mongoc_client_t
结构连接到MongoDB。
连接URI
标准的连接字符串包括以下组件
组件 | 描述 |
---|---|
mongodb+srv:// | 必需。一个前缀,用于标识此字符串为SRV连接格式的字符串。 |
username:password | |
host[:port] | 必需。MongoDB运行的主机和可选的端口号。如果不包括端口号,驱动程序将使用默认端口 27017 。 |
/defaultauthdb | 可选。如果连接字符串包含 username:password@ 身份验证凭据但未包含authSource 选项,则使用的身份验证数据库。如果不包含此组件,客户端将对admin 数据库进行用户身份验证。 |
?<options> | 可选。一个查询字符串,指定连接特定的选项,格式为 <name>=<value> 对。 |
有关创建连接字符串的更多信息,请参阅连接字符串 位于 MongoDB 服务器文档中。
Atlas 连接示例
要连接到 Atlas 上的 MongoDB 部署,您必须首先创建一个客户端。
您可以将连接 URI 作为字符串传递给 mongoc_client_new()
函数以连接到 MongoDB 实例
// Initialize the C Driver mongoc_init (); // Create a new client and connect to the server mongoc_client_t *client = mongoc_client_new ("mongodb+srv://<db_username>:<db_password>@<hostname:port>/?<options>"); mongoc_database_t *database = mongoc_client_get_database (client, "admin"); bson_t *ping = BCON_NEW ("ping", BCON_INT32 (1)); bson_t reply = BSON_INITIALIZER; bson_error_t error; // Send a ping to confirm a successful connection if (!mongoc_client_command_simple (client, "admin", ping, NULL, &reply, &error)) { fprintf(stderr, "error: %s\n", error.message); goto cleanup; } printf ("Pinged your deployment. You successfully connected to MongoDB!\n"); cleanup: bson_destroy (&reply); bson_destroy (ping); mongoc_database_destroy (database); mongoc_client_destroy (client); // Cleanup the C Driver mongoc_cleanup ();
您可以将稳定 API 版本客户端选项设置为在升级到新服务器版本时避免破坏性更改。
提示
要了解有关稳定 API 功能的更多信息,请参阅 稳定 API 指南。
以下代码演示了如何指定连接字符串和稳定 API 客户端选项以连接到 Atlas 上的 MongoDB 部署,并验证连接是否成功
// Intialize the MongoDB C Driver mongoc_init(); // Create a new client and connect to the server mongoc_client_t *client = mongoc_client_new ("mongodb+srv://<db_username>:<db_password>@<hostname:port>/?<options>"); // Set the version of the Stable API on the client mongoc_server_api_t *api = mongoc_server_api_new(MONGOC_SERVER_API_V1); bson_t *ping = BCON_NEW ("ping", BCON_INT32 (1)); bson_t reply = BSON_INITIALIZER; bson_error_t error; if (!mongoc_client_set_server_api (client, api, &error)) { fprintf(stderr, "error: %s\n", error.message); goto cleanup; } // Send a ping to confirm a successful connection if (!mongoc_client_command_simple (client, "admin", ping, NULL, &reply, &error)) { fprintf(stderr, "error: %s\n", error.message); goto cleanup; } printf ("Pinged your deployment. You successfully connected to MongoDB!\n"); cleanup: bson_destroy (&reply); bson_destroy (ping); mongoc_server_api_destroy (api); mongoc_client_destroy (client); // Cleanup the C Driver mongoc_cleanup ();
API 文档
有关 mongoc_client_t
结构的更多信息,请参阅 API 文档。