Docs Menu
Docs Home
/ / /
Java 동기화
/ /

문서 업데이트

MongoCollection 객체에서 updateOne() 메서드를 사용하여 단일 문서를 업데이트할 수 있습니다. 이 메서드는 업데이트하려는 문서와 일치하는 필터 및 일치하는 문서를 변경하는 방법을 드라이버에 지시하는 업데이트 구문을 허용합니다. updateOne() 메서드는 필터와 일치하는 첫 번째 문서만 업데이트합니다.

updateOne() 메서드로 업데이트를 수행하려면 쿼리 필터와 업데이트 문서를 전달해야 합니다. 쿼리 필터는 업데이트를 수행할 문서를 지정하는 기준을 지정하고, 업데이트 문서는 해당 문서에 어떤 변경 사항을 적용할지에 대한 지침을 제공합니다.

메서드의 동작을 지정하기 위해 선택적으로 UpdateOptions의 인스턴스를 updateOne() 메서드에 전달할 수 있습니다. 예를 들어, UpdateOptions 객체의 upsert 필드를 true로 설정했으면 쿼리 필터와 일치하는 문서가 없는 경우 작업은 쿼리와 업데이트 문서 모두에 있는 필드에서 새 문서를 삽입합니다. 자세한 내용은 이 페이지 하단의 UpdateOptions API 문서 링크를 참조하세요.

성공적으로 실행되면 updateOne() 메서드는 UpdateResult 인스턴스를 반환합니다. getModifiedCount() 메서드를 호출하여 수정된 문서 수와 같은 정보를 검색하거나 UpdateOptions 인스턴스에서 upsert(true)를 지정한 경우 getUpsertedId() 메서드를 호출하여 _id 필드의 값을 검색할 수 있습니다.

업데이트 작업이 실패하면 드라이버에서 예외가 발생합니다. 예를 들어 업데이트 문서에서 변경 불가 필드 _id 값을 설정하려고 하면 메서드에서 다음 메시지와 함께 MongoWriteException가 표시됩니다.

Performing an update on the path '_id' would modify the immutable field '_id'

업데이트 문서에 고유 색인 규칙을 위반하는 변경 내용이 포함된 경우 메서드는 다음과 같은 오류 메시지와 함께 MongoWriteException 메시지를 띄웁니다.

E11000 duplicate key error collection: ...

특정 조건에서 발생하는 예외 유형에 대한 자세한 내용은 이 페이지 하단에 링크된 updateOne() 에 대한 API 문서를 참조하세요.

이 예제에서는 sample_mflix 데이터베이스의 movies 컬렉션에서 쿼리와 일치하는 첫 번째 항목을 업데이트합니다. 일치하는 문서에 대해 다음과 같은 업데이트를 수행합니다:

  • runtime의 값을 99로 설정합니다.

  • 존재하지 않는 경우, Sportsgenres 배열에 추가합니다.

  • lastUpdated 값을 현재 시간으로 설정합니다.

정적 헬퍼 메서드가 포함된 팩토리 클래스인 Updates 빌더를 사용하여 업데이트 문서를 구성합니다. 빌더를 사용하는 대신 업데이트 문서를 전달할 수 있지만 빌더는 유형 검사 및 간소화된 구문을 제공합니다. Updates 빌더에 대한 자세한 내용은 업데이트 빌더의 가이드를 참조하세요.

참고

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

package usage.examples;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.model.UpdateOptions;
import com.mongodb.client.model.Updates;
import com.mongodb.client.result.UpdateResult;
public class UpdateOne {
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");
MongoCollection<Document> collection = database.getCollection("movies");
Document query = new Document().append("title", "Cool Runnings 2");
Bson updates = Updates.combine(
Updates.set("runtime", 99),
Updates.addToSet("genres", "Sports"),
Updates.currentTimestamp("lastUpdated"));
UpdateOptions options = new UpdateOptions().upsert(true);
try {
UpdateResult result = collection.updateOne(query, updates, options);
System.out.println("Modified document count: " + result.getModifiedCount());
System.out.println("Upserted id: " + result.getUpsertedId()); // only contains a value when an upsert is performed
} catch (MongoException me) {
System.err.println("Unable to update due to an error: " + me);
}
}
}
}

예제를 실행하면 다음과 같은 출력이 표시됩니다.

Modified document count: 1
Upserted id: null

또는 예제로 인해 업서트가 발생한 경우:

Modified document count: 0
Upserted id: BsonObjectId{value=...}

업데이트된 문서를 쿼리하면 다음과 같이 표시됩니다.

Document {
{ _id=...,
plot=...,
genres=[Adventure, Comedy, Family, Sports],
runtime=99,
...
lastUpdated=Timestamp{...}
}
}

Legacy API

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

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

  • UpdateOne

  • UpdateOptions

  • combine()

  • set()

  • addToSet()

  • currentTimestamp()

  • UpdateResult

돌아가기

업데이트 & 작업 바꾸기