문서 메뉴
문서 홈
/ / /
Kotlin Sync 드라이버
/

문서 업데이트

이 페이지의 내용

  • 개요
  • 샘플 데이터
  • 업데이트 작업
  • 하나의 문서 업데이트
  • 다수 문서 업데이트
  • 업데이트 작업 사용자 지정
  • 반환 값
  • 추가 정보
  • API 문서

이 가이드에서는 Kotlin Sync 드라이버를 사용하여 updateOne()updateMany() 메서드를 통해 MongoDB 컬렉션의 문서를 업데이트하는 방법을 배울 수 있습니다.

이 가이드의 예제에서는 Atlas 샘플 데이터 세트sample_restaurants.restaurants 컬렉션을 사용합니다. 무료 MongoDB Atlas 클러스터를 생성하고 샘플 데이터 세트를 로드하는 방법을 알아보려면 Atlas 시작하기 가이드를 참조하세요.

이 컬렉션의 문서는 다음 Kotlin 데이터 클래스에 따라 모델링됩니다.

data class Restaurant(
val name: String,
val borough: String,
val cuisine: String,
val address: Document
)

다음 방법을 사용하여 MongoDB에서 문서를 업데이트할 수 있습니다.

  • updateOne()검색 조건과 일치하는 첫 번째 문서가 업데이트됩니다.

  • updateMany()검색 조건과 일치하는 모든 문서가 업데이트됩니다.

각 업데이트 방법에는 다음 매개변수가 필요합니다.

  • 업데이트할 문서와 일치하는 쿼리 필터 입니다. 쿼리 필터에 대해 자세히 알아보려면 쿼리 지정 가이드를 참조하세요.

  • 업데이트 연산자 또는 수행할 업데이트의 종류, 업데이트할 필드 및 값을 지정하는 업데이트 문서 입니다. 업데이트 연산자 목록과 그 사용법은 MongoDB Server 매뉴얼의 필드 업데이트 연산자 가이드 페이지 를 참조하세요.

다음 예제에서는 updateOne() 메서드를 사용하여 문서의 name 값을 "Happy Garden" 에서 "Mountain House" 로 업데이트합니다.

val filter = eq(Restaurant::name.name, "Happy Garden")
val update = set(Restaurant::name.name, "Mountain House")
val result = collection.updateOne(filter, update)

다음 예제에서는 updateMany() 메서드를 사용하여 name 값이 "Starbucks" 인 모든 문서를 업데이트합니다. 이 업데이트는 address 필드의 이름을 location 로 변경합니다.

val filter = eq(Restaurant::name.name, "Starbucks")
val update = rename(Restaurant::address.name, "location")
val result = collection.updateMany(filter, update)

updateOne()updateMany() 메서드는 업데이트 작업을 구성하는 옵션을 설정하는 매개변수를 선택적으로 허용합니다. 옵션을 지정하지 않으면 드라이버는 기본 설정으로 업데이트 작업을 수행합니다.

다음 표에서는 UpdateOptions 인스턴스를 구성하는 데 사용할 수 있는 setter 메서드에 대해 설명합니다.

속성
설명
upsert()
Specifies whether the update operation performs an upsert operation if no documents match the query filter. For more information, see the upsert statement in the MongoDB Server manual.
Defaults to false
bypassDocumentValidation()
Specifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. For more information about schema validation, see Schema Validation in the MongoDB Server manual.
Defaults to false.
collation()
Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.
arrayFilters()
Provides a list of filters that you specify to select which array elements the update applies to.
hint()
Sets the index to use when matching documents. For more information, see the hint statement in the MongoDB Server manual.
let()
Provides a map of parameter names and values to set top-level variables for the operation. Values must be constant or closed expressions that don't reference document fields. For more information, see the let statement in the MongoDB Server manual.
comment()
Sets a comment to attach to the operation. For more information, see the update command fields guide in the MongoDB Server manual for more information.

다음 코드는 updateOne() 메서드를 사용하여 name 필드 값이 "Sunrise Pizzeria" 인 문서를 일치시킵니다. 그런 다음 첫 번째 일치하는 문서의 borough 값을 "Queens" 로 설정하고 cuisine 값을 "Italian" 로 설정합니다.

upsert 옵션이 true 로 설정되어 있으므로 쿼리 필터가 기존 문서와 일치하지 않는 경우 드라이버는 업데이트 문서에 지정된 필드 및 값이 있는 새 문서를 삽입합니다.

val opts = UpdateOptions().upsert(true)
val filter = eq(Restaurant::name.name, "Sunrise Pizzeria")
val update = combine(
set(Restaurant::borough.name, "Queens"),
set(Restaurant::cuisine.name, "Italian")
)
collection.updateOne(filter, update, opts)

updateOne()updateMany() 메서드는 각각 UpdateResult 객체를 반환합니다. 다음 메서드를 사용하여 UpdateResult 인스턴스의 정보에 액세스할 수 있습니다.

속성
설명
getMatchedCount()
Returns the number of documents that matched the query filter, regardless of how many updates were performed.
getModifiedCount()
Returns the number of documents modified by the update operation. If an updated document is identical to the original, it is not included in this count.
wasAcknowledged()
Returns true if the server acknowledged the result.
getUpsertedId()
Returns the _id value of the document that was upserted in the database, if the driver performed an upsert.

참고

wasAcknowledged() 메서드가 false 을 반환하는 경우 UpdateResult 인스턴스에서 다른 정보에 액세스하려고 하면 InvalidOperation 예외가 발생합니다. 서버가 쓰기 작업을 승인하지 않으면 드라이버는 이러한 값을 결정할 수 없습니다.

Kotlin 동기화 드라이버를 사용하여 문서를 업데이트하는 방법을 보여주는 실행 가능한 코드 예제를 보려면 MongoDB에 데이터 쓰기를 참조하세요.

이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

문서 삽입