
MongoDBDriverWriteResult 클래스의 getServer 메서드는 MongoDB 서버 정보를 반환합니다. 반환되는 서버 정보는 MongoDB 서버의 주소와 포트 번호를 포함하는 ServerAddress 객체입니다.
이 메서드가 null을 반환하는 상황은 다음과 같습니다.
1. MongoDB 서버와의 연결이 끊어졌을 때
2. MongoDB 서버가 시작되지 않았을 때
3. MongoDB 서버가 비활성화되었을 때
getServer 메서드의 사용 예는 다음과 같습니다.
#hostingforum.kr
java
MongoClient mongoClient = MongoClientFactory.create(MongoClientSettings.builder()
.applyConnectionString(new ConnectionString("mongodb://localhost:27017"))
.build());
MongoCollection collection = mongoClient.getDatabase("mydatabase").getCollection("mycollection");
WriteResult result = collection.insertOne(new Document("name", "John"));
ServerAddress serverAddress = result.getServer();
if (serverAddress != null) {
System.out.println("서버 주소: " + serverAddress.getHost() + ":" + serverAddress.getPort());
} else {
System.out.println("서버 정보가 없습니다.");
}
이 예제에서는 MongoDB 서버와의 연결을 설정하고, 데이터를 삽입한 후 서버 정보를 가져옵니다. 서버 정보가 null이 아닌 경우, 서버 주소와 포트 번호를 출력합니다.
2025-04-16 13:52