개요
이 가이드 에서는 C++ 운전자 사용하여 데이터베이스 명령 실행 방법을 학습 수 있습니다. 데이터베이스 명령을 사용하여 서버 통계 가져오기, 복제본 세트 초기화 또는 집계 파이프라인 실행 과 같은 다양한 관리 및 진단 작업을 수행할 수 있습니다.
중요
데이터베이스 명령보다 드라이버 메서드를 선호합니다.
드라이버는 많은 데이터베이스 명령에 대한 래퍼 메서드를 제공합니다. 가능하면 데이터베이스 명령을 실행하는 대신 드라이버 메서드를 사용하는 것이 좋습니다.
To perform administrative tasks, use the MongoDB Shell instead of the C++ driver. Calling the db.runCommand() method inside the shell is the preferred method to issue database commands, as it provides a consistent interface between the shell and drivers.
명령 실행
데이터베이스 명령 실행 하려면 mongocxx::database 인스턴스 에서 run_command() 실행 메서드를 호출하고 명령 및 관련 인수를 지정하는 문서 를 전달합니다. 이 메서드는 명령의 결과를 bsoncxx::document::value 객체 로 반환합니다.
You can use the run_command() method with any database command. For a full list of database commands and corresponding parameters, see Database Commands in the MongoDB Server manual.
다음 예시 run_command() 메서드를 사용하여 데이터베이스 에서 복제본 세트 에서 현재 멤버의 역할 에 대한 정보를 반환하는 hello 명령을 실행 방법을 보여 줍니다.
auto db = client["my_database"]; auto command = make_document(kvp("hello" , 1)); auto result = db.run_command(command.view()); std::cout << bsoncxx::to_json(result) << std::endl;
명령 옵션
To customize command execution behavior, you can set options in the command document that you pass to the run_command() method. To learn more about a command and the options that it accepts, locate the command and follow the corresponding link on the Database Commands page in the MongoDB Server manual.
예시 를 들어 명령 문서 에서 showPrivileges 옵션을 true 로 설정하여 현재 인증된 사용자가 소유한 전체 권한 설정하다 반환하도록 connectionStatus 명령에 지시할 수 있습니다.
auto db = client["my_database"]; auto command = make_document(kvp("connectionStatus" , 1), kvp("showPrivileges", true)); auto result = db.run_command(command.view()); std::cout << bsoncxx::to_json(result) << std::endl;
응답
run_command() 메서드는 명령이 실행된 후 데이터베이스 의 응답이 포함된 bsoncxx::document::value 객체 반환합니다. 각 데이터베이스 명령 서로 다른 기능을 수행하므로 응답 내용은 명령에 따라 다를 수 있습니다. 그러나 모든 응답에는 다음 필드가 있는 문서가 포함되어 있습니다.
필드 | 설명 |
|---|---|
<command result> | 데이터베이스 명령과 관련된 필드를 제공합니다. 예를 들어 |
| 명령에 성공했는지( |
| 작업의 논리적 시간을 나타냅니다. MongoDB는 논리적 시간을 사용하여 작업의 순서를 지정합니다. |
| 서명된 cluster 시간을 반환하는 문서를 제공합니다. cluster 시간은 작업 순서를 지정하는 데 사용되는 논리적 시간입니다. 이 문서에는 다음 필드가 포함되어 있습니다:
|
추가 정보
이 가이드의 개념에 대한 자세한 내용은 다음 문서를 참조하세요.
이 가이드에 설명된 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.