개요
이 가이드 에서는 연결 string 과 mongoc_client_t 객체 를 사용하여 다양한 유형의 MongoDB deployment에 연결하는 방법을 학습 수 있습니다.
Atlas
MongoDB 에서 deployment에 Atlas 연결하려면 연결 에 다음 요소를 string 포함하세요.
Atlas cluster 의 URL
MongoDB 사용자 이름
MongoDB 비밀번호
그런 다음 연결 문자열 mongoc_client_new() 함수에 전달합니다.
팁
Atlas 드라이버 연결 가이드 에 따라 연결 string 을 검색합니다.
다음 코드는 C 운전자 사용하여 Atlas cluster 에 연결하는 방법을 보여줍니다. 또한 이 코드는 mongoc_server_api_new() 함수를 사용하여 Stable API 버전을 지정합니다.
bson_t *ping = BCON_NEW("ping", BCON_INT32(1)); bson_t reply = BSON_INITIALIZER; bson_error_t error; mongoc_client_t *client = NULL; // Create a new client 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); 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);
팁
Atlas 에 연결할 때 Stable API 클라이언트 옵션을 사용하여 Atlas 새 버전의 MongoDB Server 로 업그레이드할 때 호환성이 손상되는 변경을 방지하는 것이 좋습니다. Stable API 에 대해 자세히 학습 Stable API 가이드 참조하세요.
로컬 배포
로컬 MongoDB deployment에 연결하려면 localhost 을 호스트 이름으로 사용합니다. 기본적으로 mongod 프로세스는 포트 27017 에서 실행되지만, 배포서버에 맞게 사용자 지정할 수 있습니다.
다음 코드는 C 운전자 사용하여 로컬 MongoDB deployment 에 연결하는 방법을 보여줍니다.
bson_t *ping = BCON_NEW("ping", BCON_INT32(1)); bson_t reply = BSON_INITIALIZER; bson_error_t error; mongoc_client_t *client = NULL; // Create a new client mongoc_uri_t *uri = mongoc_uri_new_with_error("mongodb://localhost:27017", &error); if (!uri) { fprintf(stderr, "failed to parse URI, error: %s\n", error.message); goto cleanup; } client = mongoc_client_new_from_uri(uri); if (!client) { 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_client_destroy(client); mongoc_uri_destroy(uri);
복제본 세트
복제본 세트 세트 멤버의 호스트 이름(또는 IP 주소)과 포트 번호를 지정합니다.
복제본 세트 에 있는 호스트의 전체 목록을 제공하는 대신 복제본 세트 에 있는 호스트를 하나 이상 지정하고 C 운전자 자동 검색을 수행하여 다른 호스트를 찾도록 지시할 수 있습니다. 운전자 자동 검색을 수행하도록 지시하려면 다음 작업 중 하나를 수행합니다.
복제본 세트의 이름을
replicaSet매개변수의 값으로 지정합니다.directConnection매개 변수의 값으로false를 지정합니다.복제본 세트에 둘 이상의 호스트를 지정합니다.
다음 예시 샘플 연결 URI를 사용하여 세 개의 서로 다른 호스트의 포트 27017 에서 실행 MongoDB 복제본 세트 myreplset에 연결합니다.
bson_t *ping = BCON_NEW("ping", BCON_INT32(1)); bson_t reply = BSON_INITIALIZER; bson_error_t error; mongoc_client_t *client = NULL; // Create a new client client = mongoc_client_new("mongodb://host01:27017,host02:27017,host03:27017/?replicaSet=myreplset"); if (!client) { 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_client_destroy(client);
mongoc_client_new() 함수는 비블로킹입니다. 복제본 세트 에 연결하면 클라이언트 배경 스레드를 사용하여 복제본 세트 에 연결하는 동안 생성자가 즉시 반환됩니다.
mongoc_client_t 객체 구성하고 해당 nodes 속성의 문자열 표현을 즉시 출력하는 경우 클라이언트 복제본 세트 멤버에 연결하는 동안 목록이 비어 있을 수 있습니다.
참고
Docker에서의 복제본 세트
복제본 세트 Docker 에서 실행되면 MongoDB 엔드포인트를 하나만 노출할 수 있습니다. 이 경우 복제본 세트 검색할 수 없습니다. 연결 URI에 directConnection=false 을(를) 지정하거나 이 옵션을 설정하지 않은 상태로 두면 애플리케이션 연결 URI에 연결되지 않을 수 있습니다.
테스트 또는 개발 환경에서 directConnection=true를 지정하여 복제본 세트에 연결할 수 있습니다. 프로덕션 환경에서는 Docker 가상 네트워크 외부에서 각 MongoDB 인스턴스에 액세스할 수 있도록 클러스터를 구성하는 것이 좋습니다.
DNS 서비스 검색
To use DNS service discovery to look up the DNS SRV record of the service you're connecting to, specify the SRV connection format in your connection string. When you specify the SRV connection format, the C driver automatically rescans for new hosts. You don't need to change the client configuration to enable this behavior.
The following code creates a new mongoc_client_t by using a connection string that uses the SRV connection format:
mongoc_client_t *client = mongoc_client_new("mongodb+srv://<hostname>");
API 문서
이 가이드 에 언급된 객체 및 함수에 대한 자세한 내용은 다음 API 문서를 참조하세요.