개요
이 가이드 에서는 updateOne() 및 updateMany() 메서드를 사용하여 MongoDB 컬렉션 의 문서를 업데이트 방법을 학습 수 있습니다.
샘플 데이터
이 가이드 의 예제에서는 매장 재고에서 페인트 색상을 나타내는 문서를 저장하는 paint_inventory 컬렉션 에 대한 작업을 실행 . 이 컬렉션 다음과 같은 샘플 문서가 포함되어 있습니다.
{ "_id": 1, "color": "red", "qty": 5, "prices": [15.99, 19.99] } { "_id": 2, "color": "purple", "qty": 8, "prices": [18.99, 22.99] } { "_id": 3, "color": "yellow", "qty": 0, "prices": [14.99, 17.99] } { "_id": 4, "color": "green", "qty": 6, "prices": [19.99, 24.99] } { "_id": 5, "color": "blue", "qty": 3, "prices": [17.99, 21.99] }
다음 코틀린 (Kotlin) 데이터 클래스는 컬렉션의 문서를 모델링합니다.
data class PaintOrder( val id: Int, val color: String, val qty: Int, val prices: List<Double> )
업데이트 작업 실행
다음 방법을 사용하여 MongoDB 에서 문서를 업데이트 할 수 있습니다.
updateOne()검색 조건과 일치하는 첫 번째 문서가 업데이트됩니다.updateMany()검색 조건과 일치하는 모든 문서가 업데이트됩니다.
각 업데이트 방법에는 다음 매개변수가 필요합니다.
업데이트 할 문서를 일치시키는 쿼리 필터하다 입니다. 쿼리 필터에 학습 보려면 쿼리 지정 가이드 를 참조하세요.
Update document, which specifies the update operator, or the kind of update to perform, and the fields and values to be updated. For a list of update operators and their usages, see the Field Update Operators in the MongoDB server manual.
이 가이드 의 예제에서는 업데이트 문서를 구성하기 위한 헬퍼 메서드를 제공하는 팩토리 클래스인 Updates 빌더를 사용합니다. Updates 빌더에 대해 자세히 학습하려면 업데이트 빌더 가이드를 참조하세요.
하나의 문서 업데이트
이 예에서는 updateOne() 메서드를 사용하여 다음 조치를 수행합니다.
color필드 값이"yellow"인 문서 와 일치합니다.Updates빌더를 사용하여 일치하는 문서의qty필드 값을1만큼 증가시킵니다.
val filter = Filters.eq(PaintOrder::color.name, "yellow") val update = Updates.inc(PaintOrder::qty.name, 1) val result = collection.updateOne(filter, update) println("Matched document count: ${result.matchedCount}") println("Modified document count: ${result.modifiedCount}")
참고
여러 문서가 updateOne() 메서드에 전달된 쿼리 필터와 일치하는 경우 작업은 첫 번째 결과만 업데이트합니다. 작업이 일치하는 문서 제어하기 위해 정렬 순서를 지정할 수 있습니다. sort 옵션에 대해 자세히 알아보려면 결과 정렬 페이지를 참조하세요.
다수 문서 업데이트
다음 예시에서는 updateMany() 메서드를 사용하여 다음 조치를 수행합니다:
빈 쿼리 필터하다 사용하여 모든 문서를 일치시킵니다.
Updates빌더를 사용하여 일치하는 모든 문서에서qty필드 값을20만큼 증가시킵니다.
val filterMany = Filters.empty() val updateMany = Updates.inc(PaintOrder::qty.name, 20) val resultMany = collection.updateMany(filterMany, updateMany) println("Matched document count: ${resultMany.matchedCount}") println("Modified document count: ${resultMany.modifiedCount}")
업데이트 작업 후 paint_inventory 컬렉션 의 문서 값은 다음과 같습니다.
{ "_id": 1, "color": "red", "qty": 25, "prices": [15.99, 19.99] } { "_id": 2, "color": "purple", "qty": 28, "prices": [18.99, 22.99] } { "_id": 3, "color": "yellow", "qty": 20, "prices": [14.99, 17.99] } { "_id": 4, "color": "green", "qty": 26, "prices": [19.99, 24.99] } { "_id": 5, "color": "blue", "qty": 23, "prices": [17.99, 21.99] }
참고
쿼리 필터하다 어떤 문서와도 일치하지 않는 경우 updateMany() 메서드는 컬렉션 의 문서를 변경하지 않습니다. 일치하는 문서가 없는 경우 upsert 옵션을 사용하여 새 문서 삽입할 수 있습니다. 이 옵션을 사용하는 예시 보려면 단일 작업에서 삽입 또는 업데이트를 참조하세요.
중요
The updateOne() and updateMany() methods cannot make changes to a document that violates unique index constraints on the collection. To learn more, see Unique Indexes in the MongoDB server manual.
배열 요소 업데이트
문서의 배열 값을 업데이트 하려면 Updates 빌더를 사용하여 수행하려는 업데이트 와 업데이트 할 배열 요소를 지정합니다. 그런 다음 updateOne() 또는 updateMany() 메서드를 호출하여 업데이트 작업을 실행 .
다음 위치 연산자를 사용하여 업데이트 배열 요소를 지정할 수 있습니다.
$: 쿼리 필터와 일치하는 첫 번째 배열 요소를 업데이트합니다.$[]: 배열 의 모든 요소를 업데이트합니다.$[<identifier>]: 필터와 일치하는 배열 요소를 업데이트합니다.
이 섹션의 예제에서는 각 위치 연산자 사용하는 방법을 보여줍니다.
첫 번째 일치하는 요소 업데이트
쿼리 필터하다 와 일치하는 첫 번째 배열 요소를 업데이트 하려면 위치($) 연산자 사용하고 쿼리 필터하다 에서 업데이트 할 배열 필드 지정합니다.
이 예에서는 다음 조치를 수행합니다.
15.99값을 포함하는prices배열 있는 문서 와 일치합니다.$위치 연산자 사용하여 일치하는 문서의prices배열 에 있는 첫 번째 값을2만큼 증가시킵니다.
val filterArrayFirst = Filters.eq(PaintOrder::prices.name, 15.99) val updateArrayFirst = Updates.inc("${PaintOrder::prices.name}.$", 2) val resultArrayFirst = collection.updateOne(filterArrayFirst, updateArrayFirst) println("Modified document count: ${resultArrayFirst.modifiedCount}")
모든 요소 업데이트
배열 의 모든 요소를 업데이트 하려면 모든 위치($[]) 연산자 사용합니다.
이 예에서는 다음 조치를 수행합니다.
color값이"green"인 문서 와 일치합니다.$[]위치 연산자 사용하여 일치하는 문서의prices배열 에 있는 모든 값에1.1를 곱합니다.
val filterArrayAll = Filters.eq(PaintOrder::color.name, "green") val update = Updates.mul("${PaintOrder::prices.name}.$[]", 1.1) val resultArrayAll = collection.updateOne(filterArrayAll, update) println("Modified document count: ${resultArrayAll.modifiedCount}")
The updateOne() and updateMany() methods cannot make changes to a document that violate unique index constraints on the collection. See the MongoDB server manual for more information on unique indexes.