以下是使用C驱动程序检查MongoDB服务器连接状态的代码示例:
#include <mongoc/mongoc.h>
int main (void)
{
mongoc_client_t *client;
bson_error_t error;
mongoc_init ();
client = mongoc_client_new ("mongodb://localhost:27017/");
if (!mongoc_client_get_server_status (client, NULL, &error)) {
printf ("Failed to get server status: %s\n", error.message);
return EXIT_FAILURE;
}
printf ("Server is connected!\n");
mongoc_client_destroy (client);
mongoc_cleanup ();
return EXIT_SUCCESS;
}
在此示例中,我们首先初始化MongoDB C驱动程序库。然后,我们创建一个mongoc_client_t对象并使用它来连接到本地主机上运行的MongoDB服务器。接下来,我们使用mongoc_client_get_server_status()函数检查与服务器的连接状态。如果连接成功,则该函数将返回true,并且我们将打印“Server is connected!”消息。否则,它将返回false,并显示错误消息。
最后,我们清理和销毁所有相关资源并返回适当的退出状态码。




