문서 메뉴
문서 홈
/ / /
Java 동기화
/

명령 실행

MongoDatabase.runCommand() 메서드를 사용하여 모든 원본 데이터베이스 작업을 실행할 수 있습니다. 원본 데이터베이스 작업은 MongoDB Server CLI에서 직접 실행할 수 있는 명령입니다. 이러한 명령에는 서버 통계 가져오기 또는 복제본 세트 초기화와 같은 관리 및 진단 작업이 포함됩니다. MongoDatabase 인스턴스에서 Bson 명령 객체와 함께 runCommand() 메서드를 호출하여 원본 데이터베이스 작업을 실행합니다.

이러한 작업은 Java 애플리케이션보다 셸을 사용하여 구현하는 것이 더 빠르고 쉬운 경우가 많으므로 가능하면 관리 작업에는 Java 드라이버 대신 MongoDB Shell을 사용합니다.

runCommand() 메서드는 Bson 객체 형식의 명령을 받습니다. 기본적으로 runCommand는 데이터베이스 명령의 출력을 포함하는 유형 org.bson.Document의 객체를 반환합니다. 선택적 두 번째 매개변수로 runCommand()의 반환 유형을 지정할 수 있습니다.

다음 샘플 코드에서는 특정 MongoDB database에서 통계를 요청하기 위해 dbStats 명령을 보냅니다.

참고

이 예제에서는 연결 URI를 사용하여 MongoDB 인스턴스에 연결합니다. MongoDB 인스턴스에 연결하는 방법에 대해 자세히 알아보려면 연결 가이드를 참조하세요.

package usage.examples;
import org.bson.BsonDocument;
import org.bson.BsonInt64;
import org.bson.Document;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoDatabase;
import org.bson.conversions.Bson;
public class RunCommand {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
try {
Bson command = new BsonDocument("dbStats", new BsonInt64(1));
Document commandResult = database.runCommand(command);
// Prints the database statistics
System.out.println("dbStats: " + commandResult.toJson());
} catch (MongoException me) {
// Prints a message if any exceptions occur during the command execution
System.err.println("An error occurred: " + me);
}
}
}
}

앞의 명령을 실행하면 다음과 유사한 출력이 표시됩니다.

dbStats: {"db": "sample_mflix", "collections": 5, "views": 0, "objects": 75595, "avgObjSize": 692.1003770090614, "dataSize": 52319328, "storageSize": 29831168, "numExtents": 0, "indexes": 9, "indexSize": 14430208, "fileSize": 0, "nsSizeMB": 0, "ok": 1}

레거시 API

레거시 API를 사용하는 경우 FAQ 페이지를 참조하여 코드 예제의 어떤 부분을 변경해야는지 확인하세요.

이 페이지에 언급된 클래스 및 메서드에 대한 추가 정보는 다음 리소스를 참조하세요.

돌아가기

필드의 고유 값 가져오기