Docs Menu

명령 실행

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

중요

데이터베이스 명령보다 드라이버 메서드를 선호합니다.

드라이버는 많은 데이터베이스 명령에 대한 래퍼 메서드를 제공합니다. 가능하면 데이터베이스 명령을 실행하는 대신 드라이버 메서드를 사용하는 것이 좋습니다.

관리 작업을 수행하려면 Java 드라이버 대신 MongoDB Shell 을 사용하세요. shell 내에서 db.runCommand() 메서드를 호출하는 것은 shell 과 드라이버 간에 일관된 인터페이스를 제공하므로 데이터베이스 명령을 실행하는 데 선호되는 방법입니다.

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

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

참고

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

// Runs a database command by using the Java driver
package org.example;
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));
// Retrieves statistics about the specified database
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}

Legacy API

레거시 API 사용하는 경우 레거시 API 가이드의 FAQ 섹션 을 참조하여 이 코드 예시에 적용해야 하는 변경 사항을 학습.

데이터베이스 명령을 실행 데 사용되는 메서드에 대한 자세한 내용은 다음 API 설명서를 참조하세요.