개요
이 가이드 에서는 Ruby 운전자 사용하여 MongoDB 컬렉션 의 문서 에서 바꾸기 작업을 수행하는 방법을 학습 수 있습니다. 바꾸기 작업은 지정된 문서 에서 필드 제외한 모든 필드와 값을 _id
제거하고 사용자가 지정한 새 필드와 값을 추가합니다. 이 작업은 하나 이상의 문서에서 지정된 필드만 변경하는 업데이트 작업과 다릅니다.
업데이트 작업에 학습 보려면 문서 업데이트 가이드 를 참조하세요.
샘플 데이터
이 가이드 의 예제에서는 restaurants
sample_restaurants
Atlas 샘플 데이터 세트의 데이터베이스 에 있는 컬렉션 사용합니다. Ruby 애플리케이션 에서 이 컬렉션 에 액세스 하려면 Mongo::Client
Atlas cluster 에 연결하는 객체 만들고 및 변수에 다음 값을 할당합니다.database
collection
database = client.use('sample_restaurants') collection = database[:restaurants]
무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 Atlas 시작하기 가이드 를 참조하세요.
대체 작업
replace_one
메서드를 사용하여 MongoDB 에서 바꾸기 작업을 수행할 수 있습니다. 이 메서드는 지정된 쿼리 필터하다 일치하는 첫 번째 문서 에서 _id
필드 제외한 모든 필드를 제거합니다. 그런 다음 지정한 필드와 값을 빈 문서 에 추가합니다.
필수 매개변수
다음 매개변수를 replace_one
메서드에 전달해야 합니다.
쿼리 필터하다: 업데이트 할 문서를 지정합니다. 쿼리 필터에 대해 자세히 학습 쿼리 지정 가이드 참조하세요.
대체 문서: 기존 필드 및 값을 대체할 필드와 값을 지정합니다.
바꾸기 예시
다음 예시 replace_one
메서드를 사용하여 name
필드 값이 "Primola Restaurant"
인 문서 의 필드와 값을 바꿉니다.
filter = { name: 'Primola Restaurant' } new_document = { name: 'Frutti Di Mare', cuisine: 'Seafood', borough: 'Queens' } result = collection.replace_one(filter, new_document) puts "Replaced #{result.modified_count} document(s)"
Replaced 1 document(s)
중요
_id
필드 의 값은 변경할 수 없습니다. 대체 문서 _id
필드 의 값을 지정하는 경우 기존 문서 의 _id
값과 동일해야 하며 그렇지 않으면 운전자 WriteError
을 발생시킵니다.
대체 작업 사용자 지정
Hash
객체 replace_one
메서드에 매개변수로 전달하여 대체 작업을 구성하는 옵션을 설정하다 수 있습니다. 옵션을 지정하지 않으면 운전자 기본값 설정으로 바꾸기 작업을 수행합니다.
다음 표에서는 바꾸기 작업을 구성하는 데 사용할 수 있는 옵션에 대해 설명합니다.
옵션 | 설명 |
---|---|
| 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 . |
| 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. |
| Specifies the session to use for the operation. To learn more about sessions, see
Client Sessions and Causal Consistency Guarantees
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. |
다음 코드는 앞의 예시 와 동일한 바꾸기 작업을 수행하지만 upsert
옵션을 true
로 설정합니다. 이는 쿼리 필터하다 기존 문서와 일치하지 않는 경우 운전자 에 대체 문서 에 지정된 필드 및 값이 있는 새 문서 삽입하도록 지시합니다.
options = { upsert: true } result = collection.replace_one(filter, new_document, options) puts "Replaced #{result.upserted_count} document(s)"
Replaced 1 document(s)
반환 값
replace_one
메서드는 Mongo::Operation::Update::Result
객체 반환합니다. 다음 메서드를 사용하여 Result
인스턴스 의 정보에 액세스 수 있습니다.
메서드 | 설명 |
---|---|
| 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 the number of documents upserted. |
| Returns the _id value of the document that the driver upserted
into the database, if any. |
추가 정보
문서 를 교체하는 방법을 보여주는 실행 가능한 코드 예시 를 보려면 MongoDB 에 데이터 쓰기를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.