개요
이 가이드 에서는 Ruby 운전자 사용하여 단일 데이터베이스 호출로 데이터를 여러 번 변경하는 대량 쓰기 (write) 작업을 수행하는 방법을 학습 수 있습니다.
동일한 작업 에 대해 문서를 삽입하고, 문서를 업데이트 , 문서를 삭제 해야 하는 상황을 생각해 보세요. 개별 쓰기 (write) 메서드를 사용하는 경우 각 쓰기 (write) 작업은 데이터베이스 별도로 액세스합니다. 대신 대량 쓰기 (write) 작업을 사용하여 애플리케이션 에서 서버 에 대해 수행하는 호출 수를 최적화할 수 있습니다.
샘플 데이터
이 가이드 의 예제에서는 Atlas 샘플 데이터 세트의 sample_restaurants
데이터베이스 에 있는 restaurants
컬렉션 사용합니다. Ruby 애플리케이션 에서 이 컬렉션 에 액세스 하려면 Atlas cluster 에 연결하는 Mongo::Client
객체 만들고 database
및 collection
변수에 다음 값을 할당합니다.
database = client.use('sample_restaurants') collection = database[:restaurants]
무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 Atlas 시작하기 가이드 를 참조하세요.
쓰기 작업 정의
수행하려는 각 쓰기 (write) 작업에 대해 다음 작업 중 하나를 구현하는 해시를 만듭니다.
insert_one
update_one
update_many
replace_one
delete_one
delete_many
그런 다음 이러한 인스턴스 목록을 bulk_write
메서드에 전달합니다.
다음 섹션에서는 이전 작업의 인스턴스를 만들고 사용하는 방법을 보여줍니다. 대량 작업 수행 섹션에서는 해시 목록을 bulk_write
메서드에 전달하여 대량 작업을 수행하는 방법을 보여 줍니다.
삽입 작업
삽입 작업을 수행하려면 insert_one
해시를 만들고 삽입하려는 문서 지정합니다.
다음 예시 insert_one
해시를 생성합니다.
insert_one = { insert_one: { name: 'Steve Rogers Cafe', borough: 'Brooklyn' } }
여러 문서를 삽입하려면 각 문서 에 대해 별도의 insert_one
해시를 만듭니다.
중요
대량 작업을 수행할 때 insert_one
작업은 컬렉션 에 이미 존재하는 _id
이(가) 있는 문서 삽입할 수 없습니다. 이 상황에서 운전자 MongoBulkWriteException
를 발생시킵니다.
업데이트 작업
문서 업데이트 하려면 update_one
해시를 만들고 다음 인수를 전달합니다.
컬렉션 의 문서를 일치시키는 데 사용되는 기준을 지정하는 쿼리 필터하다 입니다.
수행하려는 업데이트 작업입니다. 업데이트 작업에 대한 자세한 내용은 MongoDB Server 매뉴얼의 필드 업데이트 연산자 가이드 참조하세요.
update_one
작업은 쿼리 필터와 일치하는 첫 번째 문서에 대한 업데이트를 지정합니다.
다음 예시 update_one
해시를 생성합니다.
update_one = { update_one: { filter: { name: 'Mountain View' }, update: { '$set': { borough: 'Queens' } } } }
여러 문서를 업데이트 하려면 update_many
해시를 만들고 update_one
작업과 동일한 인수를 전달합니다. update_many
작업은 쿼리 필터와 일치하는 모든 문서에 대한 업데이트를 지정합니다.
다음 예시 update_many
해시를 생성합니다.
update_many = { update_many: { filter: { name: 'Starbucks' }, update: { '$set': { cuisine: 'Cafe' } } } }
대체 작업
바꾸기 작업은 지정된 문서 의 모든 필드와 값을 제거하고 사용자가 지정한 새 필드와 값으로 바꿉니다. 바꾸기 작업을 수행하려면 replace_one
해시를 만들고 다음 인수를 전달합니다.
컬렉션 의 문서를 일치시키는 데 사용되는 기준을 지정하는 쿼리 필터하다
삽입할 새 필드와 값을 지정하는 대체 문서
다음 예시 replace_one
해시를 생성합니다.
replace_one = { replace_one: { filter: { name: 'Old World Diner' }, replacement: { '$set': { name: 'New Age Luncheonette' } } } }
여러 문서를 바꾸려면 각 문서 에 대해 replace_one
해시를 만들어야 합니다.
삭제 작업
문서 삭제 하려면 delete_one
해시를 만들고 삭제 하려는 문서 지정하는 쿼리 필터하다 전달합니다. delete_one
작업은 쿼리 필터와 일치하는 첫 번째 문서 만 삭제합니다.
다음 예시 delete_one
해시를 생성합니다.
delete_one = { delete_one: { name: 'Old World Diner' } }
여러 문서를 삭제 하려면 delete_many
해시를 만들고 삭제 하려는 문서 지정하는 쿼리 필터하다 전달합니다. delete_many
작업은 쿼리 필터와 일치하는 모든 문서를 삭제합니다.
다음 예시 delete_many
해시를 생성합니다.
delete_many = { delete_many: { name: 'Starbucks' } }
대량 작업 수행
수행하려는 각 작업에 대한 해시를 정의한 후 이러한 객체 목록을 bulk_write
메서드에 전달합니다. 기본값 으로 이 메서드는 해시 목록에 지정된 순서대로 작업을 실행합니다.
다음 예시 에서는 bulk_write
메서드를 사용하여 여러 쓰기 (write) 작업을 수행합니다.
insert_one = { insert_one: { name: 'Nuovo Ristorante', borough: 'Brooklyn', cuisine: 'Italian' } } update_one = { update_one: { filter: { name: 'Moonlit Tavern' }, update: { '$set': { borough: 'Queens' } } } } delete_many = { delete_many: { name: 'Crepe' } } writes = [insert_one, update_one, delete_many] collection.bulk_write(writes)
쓰기 (write) 작업 중 하나라도 실패하면 Ruby 운전자 BulkWriteError
를 발생시키고 더 이상 작업을 수행하지 않습니다. BulkWriteError
은(는) 실패한 작업과 예외에 대한 세부 정보가 포함된 details
항목을 제공합니다.
참고
운전자 가 대량 작업을 실행할 때 대상 컬렉션 의 쓰기 고려 (write concern) 를 사용합니다. 운전자 는 실행 순서에 관계없이 모든 작업을 시도한 후 모든 쓰기 고려 (write concern) 오류를 보고합니다.
대량 쓰기 작업 사용자 지정
bulk_write
메서드는 대량 쓰기 (write) 작업을 구성하는 데 사용할 수 있는 옵션을 지정하는 options
해시를 선택적으로 허용합니다. 옵션을 지정하지 않으면 운전자 기본값 설정으로 대량 작업을 수행합니다.
다음 표에서는 bulk_write
메서드를 구성하는 데 사용할 수 있는 옵션에 대해 설명합니다.
옵션 | 설명 |
---|---|
| If true , the driver performs the write operations in the order
provided. If an error occurs, the remaining operations are not
attempted.If false , the driver performs the operations in an
arbitrary order and attempts to perform all operations.Defaults to true . |
| 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 . |
| The session to use for the operation. Type: Session |
| 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. |
다음 코드는 옵션을 생성하고 ordered
옵션을 false
로 설정하여 순서가 지정되지 않은 대량 쓰기 (write) 지정합니다. 그런 다음 이 코드는 bulk_write
메서드를 사용하여 앞의 예시 와 동일한 대량 작업을 수행합니다.
options = { ordered: false } collection.bulk_write(writes, options)
순서가 지정되지 않은 대량 쓰기 (write) 의 쓰기 (write) 작업 중 하나라도 실패하면 Ruby 운전자 모든 작업을 시도한 후에만 오류를 보고합니다.
참고
순서가 지정되지 않은 대량 작업은 실행 순서를 보장하지 않습니다. 순서는 런타임을 최적화하기 위해 나열하는 방식과 다를 수 있습니다.
반환 값
bulk_write
메서드는 BulkWrite::Result
을 반환합니다. 다음 인스턴스 메서드를 사용하여 Result
인스턴스 의 정보 액세스 수 있습니다.
메서드 | 설명 |
---|---|
| Indicates if the server acknowledged the write operation. |
| Returns the number of documents deleted, if any. |
| Returns the number of documents inserted, if any. |
| Returns the list of inserted document ids, if any. |
| Returns the number of documents matched for an update, if applicable. |
| Returns the number of documents modified, if any. |
| Returns the number of upserted documents, if any. |
| Returns the list of upserted document ids, if any. |
추가 정보
개별 쓰기 작업을 수행하는 방법을 알아보려면 다음 가이드를 참조하세요.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.