문서 업데이트
개요
이 가이드 에서는 updateOne()
및 updateMany()
메서드를 통해 스칼라 운전자 사용하여 MongoDB 컬렉션 의 문서를 업데이트 방법을 학습 수 있습니다.
샘플 데이터
이 가이드 의 예제에서는 restaurants
sample_restaurants
Atlas 샘플 데이터 세트의 데이터베이스 에 있는 컬렉션 사용합니다. 스칼라 애플리케이션 에서 이 컬렉션 액세스 하려면 MongoClient
Atlas cluster 에 연결하는 를 만들고 및 변수에 다음 값을 할당합니다.database
collection
val database: MongoDatabase = mongoClient.getDatabase("sample_restaurants") val collection: MongoCollection[Document] = database.getCollection("restaurants")
무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 Atlas 시작하기 가이드 를 참조하세요.
업데이트 작업
다음 방법을 사용하여 MongoDB 에서 문서를 업데이트 할 수 있습니다.
updateOne()
검색 조건과 일치하는 첫 번째 문서가 업데이트됩니다.updateMany()
검색 조건과 일치하는 모든 문서가 업데이트됩니다.
각 업데이트 방법에는 다음 매개변수가 필요합니다.
업데이트 하려는 문서와 일치하는쿼리 필터하다 입니다. 쿼리 필터에 대해 자세히 학습 쿼리 지정 가이드 참조하세요.
업데이트 연산자 , 업데이트할 필드 및 값을 지정하는 업데이트문서 입니다. 업데이트 연산자 수행할 업데이트 유형을 지정합니다. 업데이트 연산자 목록을 보고 사용법에 대해 학습 MongoDB Server 매뉴얼의 필드 업데이트 연산자 가이드 페이지를 참조하세요.
하나의 문서 업데이트 예시
다음 예시 updateOne()
메서드를 사용하여 문서 의 name
필드 값을 "Happy Garden"
에서 "Mountain
House"
로 업데이트 . 업데이트 문서 set()
메서드를 사용하여 name
필드 값을 업데이트 .
val filter = equal("name", "Happy Garden") val update = set("name", "Mountain House") val observable: Observable[UpdateResult] = collection.updateOne(filter, update) observable.subscribe(new Observer[UpdateResult] { override def onNext(result: UpdateResult): Unit = println(s"Updated document count: ${result.getModifiedCount}") override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}") override def onComplete(): Unit = println("Completed") })
Updated document count: 1 Completed
다수 문서 업데이트 예시
다음 예시 updateMany()
메서드를 사용하여 name
필드 값이 "Starbucks"
인 모든 문서를 업데이트 . 업데이트 문서 rename()
메서드를 사용하여 address
필드 의 이름을 location
로 변경합니다.
val filter = equal("name", "Starbucks") val update = rename("address", "location") val observable: Observable[UpdateResult] = collection.updateMany(filter, update) observable.subscribe(new Observer[UpdateResult] { override def onNext(result: UpdateResult): Unit = println(s"Updated document count: ${result.getModifiedCount}") override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}") override def onComplete(): Unit = println("Completed") })
Updated document count: 11 Completed
업데이트 작업 사용자 지정
updateOne()
및 updateMany()
메서드는 업데이트 작업을 구성하는 옵션을 설정하는 매개변수를 선택적으로 허용합니다. 옵션을 지정하지 않으면 운전자 는 기본값 설정으로 업데이트 작업을 수행합니다.
다음 표에서는 UpdateOptions
인스턴스 를 구성하는 데 사용할 수 있는 setter 메서드에 대해 설명합니다.
메서드 | 설명 |
---|---|
| 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 |
| Sets the sort criteria to apply to the operation. If multiple
documents match the query filter that you pass to the
updateOne() method, the operation updates the first
result. You can set this option to apply an order to matched
documents to have more control over which document is updated. |
| 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 . |
| Specifies the kind of language collation to use when sorting
results. For more information, see Collation
in the MongoDB Server manual. |
| Provides a list of filters that you specify to select which
array elements the update applies to. |
| Sets the index to use when matching documents.
For more information, see the hint statement
in the MongoDB Server manual. |
| 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. |
| 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()
메서드에 전달합니다. 이 예시 equal()
헬퍼 메서드를 사용하여 name
필드 값이 "Sunrise Pizzeria"
인 문서를 일치시킵니다. 그런 다음 set()
메서드를 사용하여 일치하는 첫 번째 문서 의 borough
필드 값을 "Queens"
로, cuisine
필드 값을 "Italian"
로 설정하다 . 이 코드는 combine()
메서드를 사용하여 하나의 업데이트 문서 에 여러 업데이트를 지정합니다.
UpdateOptions
인스턴스 에서 upsert
옵션이 true
로 설정하다 있으므로 운전자 필터하다 에 지정된 필드 및 값이 있는 새 문서 삽입하고 쿼리 필터하다 기존 문서와 일치하지 않는 경우 문서 업데이트 .
val filter = equal("name", "Sunrise Pizzeria") val opts = UpdateOptions().upsert(true) val update = combine( set("borough", "Queens"), set("cuisine", "Italian") ) val observable: Observable[UpdateResult] = collection.updateOne(filter, update, opts) observable.subscribe(new Observer[UpdateResult] { override def onNext(result: UpdateResult): Unit = println(s"Updated document count: ${result.getModifiedCount}") override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}") override def onComplete(): Unit = println("Completed") })
Updated document count: 1 Completed
반환 값
updateOne()
및 updateMany()
메서드는 각각 UpdateResult
객체 를 반환합니다. 다음 메서드를 사용하여 UpdateResult
인스턴스 의 정보에 액세스 할 수 있습니다.
메서드 | 설명 |
---|---|
| Returns the number of documents that matched the query filter, regardless of
how many updates were performed. |
| 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. |
| Returns true if the server acknowledged the result. |
| Returns the _id value of the document that was upserted
in the database, if the driver performed an upsert. |
참고
wasAcknowledged()
메서드가 false
을 반환하는 경우 UpdateResult
인스턴스 에서 다른 정보에 액세스 하려고 하면 InvalidOperation
예외가 발생합니다. 서버 가 쓰기 (write) 작업을 승인하지 않으면 운전자 는 이러한 값을 결정할 수 없습니다.
추가 정보
스칼라 운전자 사용하여 문서를 업데이트 방법을 보여주는 실행 가능한 코드 예제를 보려면 MongoDB 에 데이터 쓰기를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.