문서 교체
개요
이 가이드 에서는 스칼라 운전자 사용하여 MongoDB 컬렉션 의 문서 에서 바꾸기 작업을 수행하는 방법을 학습 수 있습니다. 바꾸기 작업은 지정된 문서 에서 필드 제외한 모든 필드와 값을 _id
제거하고 사용자가 지정한 새 필드와 값을 추가합니다. 이 작업은 하나 이상의 문서에서 지정된 필드만 변경하는 업데이트 작업과 다릅니다.
업데이트 작업에 학습 보려면 문서 업데이트 가이드 를 참조하세요.
샘플 데이터
이 가이드 의 예제에서는 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 시작하기 가이드 를 참조하세요.
대체 작업
replaceOne()
메서드를 사용하여 MongoDB 에서 바꾸기 작업을 수행할 수 있습니다. 이 메서드는 지정된 쿼리 필터하다 일치하는 첫 번째 문서 에서 _id
필드 제외한 모든 필드를 제거합니다. 그런 다음 지정한 필드와 값을 빈 문서 에 추가합니다.
필수 매개변수
다음 매개변수를 replaceOne()
메서드에 전달해야 합니다.
업데이트 할 문서를 일치시키는 쿼리 필터하다 입니다. 쿼리 필터에 학습 보려면 쿼리 지정 가이드 를 참조하세요.
대체 문서 는 기존 필드 및 값을 대체할 필드와 값을 지정합니다.
하나의 문서 바꾸기
다음 예시 replaceOne()
메서드를 사용하여 name
필드 값이 "Primola Restaurant"
인 문서 의 필드와 값을 바꿉니다.
val filter = equal("name", "Primola Restaurant") val replacement = Document( "name" -> "Frutti Di Mare", "borough" -> "Queens", "cuisine" -> "Seafood", "owner" -> "Sal Thomas" ) val observable: Observable[UpdateResult] = collection.replaceOne(filter, replacement) observable.subscribe(new Observer[UpdateResult] { override def onNext(result: UpdateResult): Unit = println(s"Replaced document count: ${result.getModifiedCount}") override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}") override def onComplete(): Unit = println("Completed") })
Replaced document count: 1 Completed
중요
_id
필드 의 값은 변경할 수 없습니다. 대체 문서 _id
필드 의 값을 지정하는 경우 기존 문서 의 _id
값과 동일해야 하며 그렇지 않으면 운전자 WriteError
을 발생시킵니다.
대체 작업 사용자 지정
replaceOne()
메서드는 선택적으로 ReplaceOptions
데이터 유형 의 매개변수를 허용합니다. ReplaceOptions
클래스에는 대체 옵션을 구성하는 데 사용할 수 있는 세터 메서드가 포함되어 있습니다. 옵션을 지정하지 않으면 운전자 기본값 설정으로 바꾸기 작업을 수행합니다.
다음 표에서는 ReplaceOptions
클래스의 setter 메서드에 대해 설명합니다.
메서드 | 설명 |
---|---|
| Specifies whether the replace operation performs an upsert operation if no
documents match the query filter. For more information, see upsert
behavior
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
replaceOne() method, the operation replaces the first
result. You can set this option to apply an order to matched
documents to have more control over which document is replaced. |
| 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. |
| 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. |
| Sets a comment to attach to the operation. |
다음 코드는 upsert
옵션을 true
로 설정하여 쿼리 필터하다 가 기존 문서와 일치하지 않는 경우 대체 문서 에 지정된 필드 및 값이 있는 새 문서 를 삽입하도록 운전자 에 지시합니다.
val options = ReplaceOptions().upsert(true) val observable: Observable[UpdateResult] = collection.replaceOne(filter, replacement, options) observable.subscribe(new Observer[UpdateResult] { override def onNext(result: UpdateResult): Unit = println(s"Replaced document count: ${result.getModifiedCount}") override def onError(e: Throwable): Unit = println(s"Failed: ${e.getMessage}") override def onComplete(): Unit = println("Completed") })
Replaced document count: 1 Completed
반환 값
replaceOne()
메서드는 UpdateResult
객체 를 반환합니다. 다음 메서드를 사용하여 UpdateResult
인스턴스 의 정보에 액세스 할 수 있습니다.
메서드 | 설명 |
---|---|
| Returns the number of documents that matched the query filter. |
| 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 the driver upserted
into the database, if any. |
추가 정보
문서 를 교체하는 방법을 보여주는 실행 가능한 코드 예시 를 보려면 MongoDB 에 데이터 쓰기를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.