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

문서 교체하기

MongoCollection 객체에서 replaceOne() 메서드를 사용하여 단일 문서를 바꿀 수 있습니다. 이 메서드는 문서에서 모든 기존 필드와 값( _id 필드 제외)을 제거하고 대체 문서로 대체합니다.

replaceOne() 메서드는 대체하려는 문서와 일치하는 쿼리 필터 및 일치하는 문서 대신 저장하려는 데이터가 포함된 대체 문서를 허용합니다. replaceOne() 메서드는 필터와 일치하는 첫 번째 문서만 대체합니다.

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

성공적으로 실행되면 replaceOne() 메서드는 UpdateResult 인스턴스를 반환합니다. getModifiedCount() 메서드를 호출하여 수정된 문서 수와 같은 정보를 검색할 수 있습니다. ReplaceOptions 인스턴스에 upsert(true) 을 설정하고 작업으로 인해 새 문서가 삽입된 경우 getUpsertedId() 메서드를 호출하여 문서의 _id 필드 값을 검색할 수도 있습니다.

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

After applying the update, the (immutable) field '_id' was found to have been altered to _id: ObjectId('...)

교체 문서에 고유 인덱스 규칙을 위반하는 변경 사항이 포함된 경우 메서드는 다음과 같은 오류 메시지와 함께 MongoWriteException 를 발생시킵니다.

E11000 duplicate key error collection: ...

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

이 예에서는 sample_mflix 데이터베이스의 movies 컬렉션에 있는 쿼리 필터와 일치하는 첫 번째 항목을 대체 문서로 바꿉니다. _id 필드를 제외한 모든 필드는 원본 문서에서 삭제되고 대체 문서로 대체됩니다.

replaceOne() 작업이 실행되기 전에는 원본 문서에 영화를 설명하는 여러 필드가 포함되어 있습니다. 작업이 실행된 후 결과 문서에는 대체 문서(titlefullplot)와 _id 필드로 지정된 필드만 포함됩니다.

다음 스니펫은 다음 객체와 메서드를 사용합니다:

  • replaceOne() 메서드에 전달되는 쿼리 필터입니다 . eq 필터는 제목이 'Music of the Heart' 텍스트와 정확히 일치하는 영화만 일치합니다.

  • 일치하는 문서가 있는 경우 이를 대체하는 문서가 포함된 대체 문서 입니다.

  • upsert 옵션이 true 로 설정된 ReplaceOptions 객체입니다. 이 옵션은 쿼리 필터가 어떤 문서와도 일치하지 않는 경우 메서드에서 대체 문서에 포함된 데이터를 삽입하도록 지정합니다.

참고

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

package usage.examples;
import static com.mongodb.client.model.Filters.eq;
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.ReplaceOptions;
import com.mongodb.client.result.UpdateResult;
public class ReplaceOne {
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 = eq("title", "Music of the Heart");
Document replaceDocument = new Document().
append("title", "50 Violins").
append("fullplot", " A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music");
ReplaceOptions opts = new ReplaceOptions().upsert(true);
UpdateResult result = collection.replaceOne(query, replaceDocument, opts);
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 replace due to an error: " + me);
}
}
}

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

Modified document count: 1
Upserted id: null

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

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

대체된 문서를 쿼리하면 다음과 같이 표시됩니다.

Document {
{ _id=...,
title=50 Violins,
fullplot=A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music
}
}

Legacy API

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

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

  • replaceOne

  • ReplaceOptions

  • UpdateResult

  • eq()

돌아가기

여러 문서 업데이트하기