데이터베이스 명령 실행
개요
이 가이드 에서는 C 운전자 사용하여 데이터베이스 명령 실행 방법을 학습 수 있습니다. 데이터베이스 명령을 사용하여 서버 통계 가져오기, 복제본 세트 초기화 또는 집계 파이프라인 실행 과 같은 다양한 관리 및 진단 작업을 수행할 수 있습니다.
중요
데이터베이스 명령보다 드라이버 함수 선호
운전자 많은 데이터베이스 명령에 대한 래퍼 함수를 제공합니다. 가능하면 데이터베이스 명령을 실행하는 대신 운전자 함수를 사용하는 것이 좋습니다.
관리 작업을 수행하려면 C 운전자 대신 MongoDBShell 사용합니다. 셸 내에서 db.runCommand()
메서드를 호출하는 것은 셸 과 드라이버 간에 일관적인 인터페이스를 제공하므로 데이터베이스 명령을 실행하는 데 선호되는 메서드입니다.
명령 실행
데이터베이스 명령 실행 하려면 BSON 문서 에 명령과 관련 매개변수를 지정한 다음 이 BSON 문서 명령 실행 함수에 전달해야 합니다. C 운전자 데이터베이스 명령을 실행 위해 다음과 같은 기능을 제공합니다.
mongoc_client_command_simple()
서버 에서 지정된 명령을 실행하고 결과의 첫 번째 문서reply
BSON 문서 에 저장합니다. 이 함수는 서버 에 직접 명령을 보내는 간단한 방법을 제공합니다.mongoc_client_command_with_opts()
서버 에서 지정된 명령을 실행하고 MongoDB 서버 버전에 따라opts
을 해석합니다. 이 기능은 추가 옵션을 허용하여 유연성을 제공합니다.
다음 코드는 mongoc_client_command_simple()
함수를 사용하여 복제본 세트 에서 현재 멤버의 역할 에 대한 정보를 반환하는 hello
명령을 데이터베이스 에서 실행 방법을 보여줍니다.
bson_t reply; bson_error_t error; bson_t *command = BCON_NEW ("hello", BCON_INT32 (1)); bool retval = mongoc_client_command_simple (client, "admin", command, NULL, &reply, &error); if (!retval) { fprintf (stderr, "Failed to run command: %s\n", error.message); } else { char *str = bson_as_canonical_extended_json (&reply, NULL); printf ("%s\n", str); bson_free (str); } bson_destroy (command); bson_destroy (&reply);
데이터베이스 명령 및 해당 매개변수의 전체 목록은 추가 정보 섹션을 참조하십시오.
명령 옵션
mongoc_client_command_with_opts()
함수에 대한 선택적 명령 동작을 지정할 수 있습니다. 이 함수는 opts
매개변수에 대한 BSON 문서 허용합니다.
다음 옵션을 지정하는 BSON 문서 전달할 수 있습니다.
readConcern
writeConcern
sessionId
collation
serverId
명령과 해당 명령이 허용하는 옵션에 대해 자세히 학습 해당 명령을 찾아 서버 매뉴얼의 데이터베이스 명령 섹션에 있는 링크를 클릭하세요.
다음 코드는 majority
쓰기 고려 (write concern) 사용하여 grantRolesToUsers
명령을 지정하는 방법을 보여줍니다.
bson_t reply; bson_error_t error; bson_t *command = BCON_NEW( "grantRolesToUser", BCON_UTF8("user011"), "roles", "[", BCON_UTF8("readWrite"), "]" ); mongoc_write_concern_t *write_concern = mongoc_write_concern_new(); mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY); bson_t *opts = bson_new(); mongoc_write_concern_append(write_concern, opts); bool retval = mongoc_client_command_with_opts(client, "admin", command, NULL, opts, &reply, &error); if (!retval) { fprintf(stderr, "Failed to run command: %s\n", error.message); } else { char *str = bson_as_canonical_extended_json(&reply, NULL); printf("Command Result: %s\n", str); bson_free(str); } bson_destroy(command); bson_destroy(opts); bson_destroy(&reply); mongoc_write_concern_destroy (write_concern);
참고
읽기 설정
mongoc_client_command_simple()
및 mongoc_client_command_with_opts()
함수는 클라이언트 에서 설정하다 했을 수 있는 읽기 설정 (read preference) 설정을 무시합니다. 기본값 으로 이러한 함수는 primary
읽기 설정 (read preference) 사용합니다.
프라이머리 읽기 설정 (read preference) 이외의 읽기 설정 (read preference) 지정하려면 이를 인수로 명시적으로 전달해야 합니다. 다음 코드는 읽기 설정 (read preference) 지정하고 이를 mongoc_client_command_simple()
함수와 함께 사용하는 방법을 보여줍니다.
read_prefs = mongoc_read_prefs_new(MONGOC_READ_SECONDARY); command = BCON_NEW("hello", BCON_INT32(1)); retval = mongoc_client_command_simple(client, "admin", command, read_prefs, &reply, &error);
읽기 설정 옵션에 대한 자세한 내용은 MongoDB Server 매뉴얼의 읽기 설정 을 참조하세요.
응답
각 함수는 명령이 실행된 후 BSON 문서 또는 데이터베이스 의 응답이 포함된 커서 반환합니다. 각 데이터베이스 명령 서로 다른 기능을 수행하므로 응답 내용은 명령에 따라 다를 수 있습니다. 그러나 모든 응답에는 다음 필드가 있는 문서가 포함되어 있습니다.
<command result>
: 데이터베이스 명령 과 관련된 필드를 제공합니다. 예시 들어count
은n
필드 반환하고explain
는queryPlanner
필드 반환합니다.ok
: 명령이 성공했는지(1
) 또는 실패했는지(0
) 여부를 나타냅니다.
예시
다음 코드는 mongoc_client_write_command_with_opts()
함수를 사용하여 writeConcern
옵션으로 cloneCollectionAsCapped
명령을 실행 방법을 보여줍니다. 그런 다음 mongoc_client_read_command_with_opts()
함수를 사용하여 collation
및 readConcern
옵션과 함께 distinct
명령을 실행 .
1 bson_t reply; 2 bson_error_t error; 3 4 bson_t *cmd = BCON_NEW ("cloneCollectionAsCapped", 5 BCON_UTF8 ("my_collection"), 6 "toCollection", 7 BCON_UTF8 ("my_capped_collection"), 8 "size", 9 BCON_INT64 (1024 * 1024)); 10 11 /* Includes write concern "majority" in command options */ 12 mongoc_write_concern_t *write_concern = mongoc_write_concern_new (); 13 mongoc_write_concern_set_w (write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY); 14 bson_t *opts = bson_new (); 15 mongoc_write_concern_append (write_concern, opts); 16 17 if (mongoc_client_write_command_with_opts (client, "test", cmd, opts, &reply, &error)) { 18 char *str = bson_as_canonical_extended_json (&reply, NULL); 19 printf ("cloneCollectionAsCapped: %s\n", str); 20 bson_free (str); 21 } else { 22 fprintf (stderr, "cloneCollectionAsCapped: %s\n", error.message); 23 } 24 25 bson_free (cmd); 26 bson_free (opts); 27 bson_destroy (&reply); 28 29 /* Defines distinct values of "x" in "my_collection" where "y" sorts after "one" */ 30 cmd = BCON_NEW ("distinct", 31 BCON_UTF8 ("my_collection"), 32 "key", 33 BCON_UTF8 ("x"), 34 "query", 35 "{", 36 "y", 37 "{", 38 "$gt", 39 BCON_UTF8 ("one"), 40 "}", 41 "}"); 42 43 mongoc_read_prefs_t *read_prefs = mongoc_read_prefs_new (MONGOC_READ_SECONDARY); 44 45 /* Specifies "One" sorts after "one" to override default behavior */ 46 opts = BCON_NEW ("collation", "{", "locale", BCON_UTF8 ("en_US"), "caseFirst", BCON_UTF8 ("lower"), "}"); 47 48 /* Adds a read concern to "opts" */ 49 mongoc_read_concern_t *read_concern = mongoc_read_concern_new (); 50 mongoc_read_concern_set_level (read_concern, MONGOC_READ_CONCERN_LEVEL_MAJORITY); 51 mongoc_read_concern_append (read_concern, opts); 52 53 if (mongoc_client_read_command_with_opts (client, "test", cmd, read_prefs, opts, &reply, &error)) { 54 char* str = bson_as_canonical_extended_json (&reply, NULL); 55 printf ("distinct: %s\n", str); 56 bson_free (str); 57 } else { 58 fprintf (stderr, "distinct: %s\n", error.message); 59 } 60 61 bson_destroy (cmd); 62 bson_destroy (opts); 63 bson_destroy (&reply); 64 mongoc_read_prefs_destroy (read_prefs); 65 mongoc_read_concern_destroy (read_concern); 66 mongoc_write_concern_destroy (write_concern);
출력
cloneCollectionAsCapped
명령은 컬렉션 을 고정 사이즈 컬렉션 으로 복제합니다. 그런 다음 distinct
명령은 지정된 필터하다 및 데이터 정렬을 사용하여 필드 의 고유 값을 가져옵니다. 이 예시 다음과 같은 결과가 출력됩니다.
cloneCollectionAsCapped: { "ok": 1, ... } distinct: { "values": ["value1", "value2", "value3"], "ok": 1, ... }
추가 정보
이 가이드의 개념에 대한 자세한 내용은 다음 문서를 참조하세요.