개요
이 가이드 에서는 Ruby 운전자 사용하여 삭제 작업을 수행하여 MongoDB 컬렉션 에서 문서를 제거 방법을 학습 수 있습니다.
삭제 작업은 MongoDB 컬렉션에서 하나 이상의 문서를 제거합니다. delete_one
또는 delete_many
메서드를 사용하여 삭제 작업을 수행할 수 있습니다.
샘플 데이터
이 가이드 의 예제에서는 Atlas 샘플 데이터 세트의 sample_restaurants
데이터베이스 에 있는 restaurants
컬렉션 사용합니다. Ruby 애플리케이션 에서 이 컬렉션 에 액세스 하려면 Atlas cluster 에 연결하는 Mongo::Client
객체 만들고 database
및 collection
변수에 다음 값을 할당합니다.
database = client.use('sample_restaurants') collection = database[:restaurants]
무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 Atlas 시작하기 가이드 를 참조하세요.
삭제 작업
다음 방법을 사용하여 MongoDB에서 삭제 작업을 수행할 수 있습니다.
delete_one
Atlas Search 기준과 일치 하는 첫 번째 문서를 삭제합니다.delete_many
Atlas Search 기준과 일치하는 모든 문서 를 삭제합니다.
각 삭제 메서드에는 제거하기 위해 선택할 문서를 결정하는 검색 기준을 지정하는 쿼리 필터 매개 변수가 필요합니다. 쿼리 필터에 대해 자세히 학습 쿼리 지정 가이드 참조하세요.
문서 하나 삭제
다음 예시 에서는 delete_one
메서드를 사용하여 name
필드 값이 "Happy Garden"
인 문서 를 제거 합니다.
filter = { name: 'Happy Garden' } result = collection.delete_one(filter) puts "Deleted #{result.deleted_count} document(s)"
Deleted 1 document(s)
여러 문서 삭제
다음 예시 에서는 delete_many
메서드를 사용하여 borough
필드 의 값이 "Brooklyn"
이고 name
필드 의 값이 "Starbucks"
인 모든 문서를 제거 합니다.
filter = { name: 'Starbucks', borough: 'Brooklyn' } result = collection.delete_many(filter) puts "Deleted #{result.deleted_count} document(s)"
Deleted 3 document(s)
삭제 작업 사용자 지정
Hash
객체 delete_one
및 delete_many
메서드에 매개 변수로 전달하여 삭제 작업을 구성하는 옵션을 설정하다 . 옵션을 지정하지 않으면 운전자 기본값 설정으로 삭제 작업을 수행합니다.
다음 표에서는 삭제 작업을 구성하는 데 사용할 수 있는 옵션에 대해 설명합니다.
옵션 | 설명 |
---|---|
| 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. |
| Specifies the index to use when matching documents.
For more information, see the hint
option in the delete reference page of 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 option in the delete
reference page of the MongoDB Server manual. |
수정 삭제 예시
다음 코드는 삭제 작업에 "name_index"
인덱스 사용하도록 지시하는 hint
옵션을 지정합니다. 그런 다음 이 예시 에서는 delete_many
메서드를 사용하여 "Red"
문자열이 포함된 name
필드 값이 있는 restaurants
컬렉션 의 모든 문서를 삭제 .
filter = { name: /Red/ } options = { hint: 'name_index' } result = collection.delete_many(filter, options) puts "Deleted #{result.deleted_count} document(s)"
Deleted 124 document(s)
팁
앞의 예시 에서 delete_many
메서드 대신 delete_one
메서드를 사용하는 경우 운전자 는 쿼리 필터하다 와 일치하는 첫 번째 문서 만 삭제합니다.
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.