문서 메뉴
문서 홈
/ / /
Java 동기화 드라이버
/

명령 실행

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 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));
// 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}

레거시 API

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

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

← 필드의 고유 값 가져오기