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

여러 문서 업데이트하기

MongoCollection 객체에서 updateMany() 메서드를 사용하여 여러 문서를 업데이트할 수 있습니다. 이 메서드는 업데이트하려는 문서와 일치하는 필터 및 일치하는 문서를 변경하는 방법을 드라이버에 지시하는 업데이트 구문을 허용합니다. updateMany() 메서드는 필터와 일치하는 컬렉션의 모든 문서를 업데이트합니다.

updateMany() 메서드로 업데이트를 수행하려면 쿼리 필터와 업데이트 문서를 전달해야 합니다. 쿼리 필터는 collection에서 일치시킬 문서를 지정하고 업데이트 문서는 문서에 적용할 변경 사항에 대한 지침을 제공합니다.

호출 동작을 수정하기 위해 선택적으로 UpdateOptions 인스턴스를 updateMany() 메서드에 전달할 수 있습니다. 예를 들어 UpdateOptions 객체의 upsert 필드를 true로 설정했는데 지정된 쿼리 필터와 일치하는 문서가 없는 경우, 작업은 쿼리와 업데이트 문서 모두의 필드로 구성된 새 문서를 삽입합니다.

성공적으로 실행되면 updateMany() 메서드는 UpdateResult 인스턴스를 반환합니다. getModifiedCount() 메서드를 호출하여 수정된 문서 수와 같은 정보를 검색할 수 있습니다. UpdateOptions 객체에 upsert(true)를 지정했는데 그 결과로 삽입 작업이 이뤄지는 경우, UpdateResult 인스턴스에서 getUpsertedId() 메서드를 호출하여 새 문서의 _id 필드를 검색할 수 있습니다.

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

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

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

E11000 duplicate key error collection: ...

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

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

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

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

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

참고

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

package usage.examples;
import static com.mongodb.client.model.Filters.gt;
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.Updates;
import com.mongodb.client.result.UpdateResult;
public class UpdateMany {
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");
Bson query = gt("num_mflix_comments", 50);
Bson updates = Updates.combine(
Updates.addToSet("genres", "Frequently Discussed"),
Updates.currentTimestamp("lastUpdated"));
try {
UpdateResult result = collection.updateMany(query, updates);
System.out.println("Modified document count: " + result.getModifiedCount());
} catch (MongoException me) {
System.err.println("Unable to update due to an error: " + me);
}
}
}
}

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

Modified document count: 53

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

[
Document {
{ _id=...,
plot=...,
genres=[..., Frequently Discussed, ...],
...
lastUpdated=Timestamp{...}
}
},
...
]

Legacy API

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

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

  • UpdateMany

  • UpdateOptions

  • combine()

  • addToSet()

  • currentTimestamp()

  • UpdateResult

돌아가기

문서 업데이트