Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
루비 드라이버
/

문서 업데이트

이 가이드 에서는 Ruby 운전자 사용하여 update_oneupdate_many 메서드를 통해 MongoDB 컬렉션 의 문서를 업데이트 방법을 학습 수 있습니다.

이 가이드 의 예제에서는 Atlas 샘플 데이터 세트sample_restaurants 데이터베이스 에 있는 restaurants 컬렉션 사용합니다. Ruby 애플리케이션 에서 이 컬렉션 에 액세스 하려면 Atlas cluster 에 연결하는 Mongo::Client 객체 만들고 databasecollection 변수에 다음 값을 할당합니다.

database = client.use('sample_restaurants')
collection = database[:restaurants]

무료 MongoDB Atlas cluster 를 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 보려면 Atlas 시작하기 가이드 를 참조하세요.

다음 방법을 사용하여 MongoDB 에서 문서를 업데이트 할 수 있습니다.

  • update_one: 검색 기준과 일치하는 첫 번째 문서 를 업데이트합니다.

  • update_many: 검색 기준과 일치하는 모든 문서 를 업데이트합니다.

각 업데이트 방법에는 다음 매개변수가 필요합니다.

  • 업데이트 하려는 문서와 일치하는쿼리 필터하다 입니다. 쿼리 필터에 대해 자세히 학습 쿼리 지정 가이드 참조하세요.

  • 업데이트 연산자, 업데이트할 필드 및 값을 지정하는 업데이트 문서 입니다. 업데이트 연산자 수행할 업데이트 유형을 지정합니다. 업데이트 연산자 목록을 보고 사용법에 대해 학습 MongoDB Server 매뉴얼의 필드 업데이트 연산자 가이드 페이지를 참조하세요.

다음 예시 update_one 메서드를 사용하여 name 필드 의 값이 "Happy Garden"인 첫 번째 문서 찾습니다. 그런 다음 $set 연산자 사용하여 name 필드 값을 "Mountain House"(으)로 업데이트 .

filter = { name: 'Happy Garden' }
update = { '$set' => { name: 'Mountain House' } }
single_result = collection.update_one(filter, update)
puts "#{single_result.modified_count} document(s) updated."
1 document(s) updated

다음 예시 update_many 메서드를 사용하여 name 필드 값이 "Starbucks"인 모든 문서를 업데이트 . 업데이트 문서 $rename 연산자 사용하여 address 필드 의 이름을 location로 변경합니다.

filter = { name: 'Starbucks' }
update = { '$rename' => { address: 'location' } }
many_result = collection.update_many(filter, update)
puts "#{many_result.modified_count} document(s) updated."
11 document(s) updated

update_oneupdate_many 메서드는 업데이트 작업을 구성하는 옵션을 허용합니다. 이러한 옵션을 개별적으로 매개 변수로 전달하거나 옵션이 포함된 Hash 객체 만들어 객체 매개 변수로 전달할 수 있습니다. 옵션을 지정하지 않으면 운전자 기본값 설정으로 업데이트 작업을 수행합니다.

다음 표에서는 업데이트 작업을 구성하는 데 사용할 수 있는 옵션에 대해 설명합니다.

옵션
설명

upsert

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.
Default: false

bypass_document_validation

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.
Default: false

collation

Language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.

array_filters

List of filters that you specify to select which array elements the update applies to.

hint

Index to use when matching documents. For more information, see the hint statement in the MongoDB Server manual.

let

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.

이 예시 $equal 연산자 사용하여 name 필드 값이 "Sunrise Pizzeria"인 문서를 일치시킵니다. 그런 다음 $set 연산자 사용하여 일치하는 첫 번째 문서 의 borough 필드 값을 "Queens" 로, cuisine 필드 값을 "Italian"로 설정하다 .

upsert 옵션이 true로 설정하다 있기 때문에 쿼리 필터하다 기존 문서와 일치하지 않는 경우 운전자 필터하다 의 필드와 값이 포함된 새 문서 삽입하고 문서를 업데이트 .

filter = { 'name' => 'Sunrise Pizzeria' }
update = { '$set' => { borough: 'Queens', cuisine: 'Italian' } }
upsert_result = collection.update_one(filter, update, upsert: true)
puts "#{upsert_result.modified_count} document(s) updated."
1 document(s) updated

update_oneupdate_many 메서드는 각각 Result 객체 반환합니다. Result 인스턴스 에서 다음 메서드 액세스 할 수 있습니다.

메서드
설명

matched_count

Number of documents that matched the query filter, regardless of how many updates were performed.

modified_count

Number of documents modified by the update operation. If an updated document is identical to the original, it is not included in this count.

acknowledged?

Returns true if the server acknowledged the result.

upserted_count

Returns the number of documents that were upserted in the database, if the driver performed an upsert.

upserted_ids

Returns the _id value of the document that was upserted in the database, if the driver performed an upsert.

다른 Result 메서드를 호출하기 전에 acknowledged? 메서드의 값을 확인하세요. acknowledged? 메서드가 false을 반환하고 Result 객체 에서 다른 메서드를 호출하려고 하면 운전자 InvalidOperation 예외가 발생합니다. 서버 쓰기 (write) 작업을 승인하지 않으면 운전자 이러한 값을 결정할 수 없습니다.

Ruby 운전자 사용하여 문서를 업데이트 방법을 보여주는 실행 가능한 코드 예제를 보려면 MongoDB 에 데이터 쓰기를 참조하세요.

이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

문서 교체

이 페이지의 내용