Overview
本页包含的代码示例展示了如何使用C驱动程序通过指定各种设置将应用程序连接到MongoDB。
提示
连接选项
要了解有关此页面上的连接选项的更多信息,请参阅每个部分中提供的链接。
要使用此页面中的连接示例,请将代码示例复制到示例应用程序或您自己的应用程序中。 请务必将代码示例中的所有占位符(例如 <hostname> )替换为 MongoDB 部署的相关值。
示例应用程序
您可以使用以下示例应用程序来测试本页上的代码示例。 要使用示例应用程序,请执行以下步骤:
确保已安装C驱动程序。
复制以下代码并将其粘贴到新的
.c文件中。从此页面复制代码示例,并将其粘贴到文件中的指定行。
1 2 3 4 int main(void) { 5 6 mongoc_uri_t* uri = NULL; 7 mongoc_client_t *client = NULL; 8 mongoc_database_t *database = NULL; 9 bson_t *ping = NULL, reply = BSON_INITIALIZER; 10 bson_error_t error; 11 12 mongoc_init(); 13 14 // Start example code here 15 16 // End example code here 17 18 if (!client) { 19 fprintf(stderr, "client initialization failure\n"); 20 goto cleanup; 21 } 22 23 database = mongoc_client_get_database(client, "admin"); 24 25 ping = BCON_NEW("ping", BCON_INT32(1)); 26 27 if (!mongoc_client_command_simple(client, "admin", ping, NULL, &reply, &error)) { 28 fprintf(stderr, "%s\n", error.message); 29 goto cleanup; 30 } 31 printf("Pinged your deployment. You successfully connected to MongoDB!\n"); 32 33 cleanup: 34 bson_destroy(&reply); 35 bson_destroy(ping); 36 mongoc_database_destroy(database); 37 mongoc_client_destroy(client); 38 mongoc_uri_destroy(uri); 39 mongoc_cleanup(); 40 }
连接
以下部分介绍如何连接到不同的目标,例如MongoDB的本地实例或Atlas上的云托管实例。
本地部署
以下代码显示了用于连接到 本地实例的连接string MongoDB:
client = mongoc_client_new("mongodb://localhost:27017");
Atlas
以下代码显示了用于连接到 上托管的部署的连接string Atlas:
client = mongoc_client_new("mongodb+srv://<db_username>:<db_password>@<hostname>/?<options>");
如需学习;了解有关连接Atlas 的更多信息,请参阅《选择连接目标》指南中的Atlas 。
副本集(Replica Set)
以下代码显示了用于连接到副本集的连接string :
client = mongoc_client_new("mongodb+srv://<replica-set-member>/?replicaSet=<replica_set_name>");
传输层安全性 (TLS)
以下部分介绍了如何在启用 TLS协议的情况下连接到MongoDB 。
要学习有关将 TLS 与 C 驱动程序结合使用的更多信息,请参阅配置传输层安全 (TLS)。
启用 TLS
以下标签页演示了如何在连接上启用TLS:
要了解有关启用 TLS 的更多信息,请参阅 TLS 配置指南中的启用 TLS 。
禁用主机名验证
以下标签页演示了如何在使用 TLS 连接时禁用主机名验证:
网络压缩
以下部分介绍了如何在指定网络压缩算法时连接到MongoDB 。
压缩算法
以下标签页演示了如何在连接到MongoDB时指定所有可用的压缩器:
zlibCompressionLevel
以下标签页演示了如何为zlib压缩器指定压缩级别:
服务器选择
以下代码显示了指定服务器选择函数的连接string :
client = mongoc_client_new("mongodb://<db_username>:<db_password>@<hostname>/?server_selector=<selector_function>");
Stable API
以下代码展示了如何在mongoc_client_t实例中指定 Stable API设置:
client = mongoc_client_new("mongodb+srv://<db_username>:<db_password>@<hostname>/?<options>"); // Set the version of the Stable API on the client mongoc_server_api_t *api = mongoc_server_api_new(MONGOC_SERVER_API_V1); mongoc_client_set_server_api(client, api, &error); // Do database work here mongoc_server_api_destroy(api);
要了解有关stable API的更多信息,请参阅stable API 。