문서 메뉴

문서 홈애플리케이션 개발MongoDB 드라이버Ruby MongoDB Driver

CRUD 작업

이 페이지의 내용

  • 키-값 쌍 표기법
  • 문서 생성
  • 쿼리 캐시
  • 읽기
  • 업데이트 중
  • 삭제
  • 쓰기 고려
  • 점/마침표(.) 및 달러 기호($)가 있는 필드 이름
  • BSON 기호 유형에 대한 참고 사항

CRUD 작업은 문서 생성, 읽기, 업데이트 및 삭제를 처리하는 작업입니다.

키-값 쌍은 MongoDB Ruby 드라이버의 다양한 컨텍스트에 나타나며, 표기 방법과 관련하여 사용 중인 Ruby 버전에 따라 몇 가지 구문상의 단점이 있습니다.

문서를 작성할 때 다음 구문은 Ruby 버전 1.9 이상에서 사용할 수 있으며 정확합니다.

document = { name: "Harriet", age: 36 }

Ruby 버전 2.2 이상을 사용하는 경우 선택적으로 키를 따옴표로 묶을 수 있습니다.

document = { "name": "Harriet", "age": 36 }

$set, $gte 또는 $near 와 같이 $ 로 시작하는 MongoDB 연산자를 사용해야 하는 경우에는 따옴표로 묶어야 합니다. Ruby 버전 2.2 이상을 사용하는 경우 다음과 같이 표기할 수 있습니다.

collection.update_one({ name: "Harriet" }, { "$set": { age: 42 } })

이전 버전의 Ruby를 사용하는 경우 해시로켓 기호를 사용하세요.

collection.update_one({ name: "Harriet" }, { "$set" => { age: 42 } })

키-값 쌍에 대한 따옴표 붙은 문자열과 해시로켓은 모든 버전의 Ruby에서 작동합니다.

collection.update_one({ "name" => "Harriet" }, { "$set" => { age: 42 } })

컬렉션에 문서를 삽입하려면 클라이언트에서 컬렉션을 선택하고 insert_one 또는 insert_many 을(를) 호출합니다.

삽입 작업은 삽입 자체에 대한 정보를 제공하는 Mongo::Operation::Result 객체를 반환합니다.

MongoDB 2.6 이상에서는 삽입이 실패하면 쓰기 명령이 사용되기 때문에 예외가 발생합니다.

MongoDB 2.4, 삽입이 실패하고 쓰기 고려 가 1 이상인 경우에만 예외가 발생합니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
result = client[:artists].insert_one( { :name => 'FKA Twigs' } )
result.n # returns 1, because 1 document was inserted.
result = client[:artists].insert_many([
{ :name => 'Flying Lotus' },
{ :name => 'Aphex Twin' }
])
result.inserted_count # returns 2, because 2 documents were inserted.

버전 3.4에 새로 추가되었습니다.

십진수128 은(는) 정확한 정밀도로 십진수 반올림을 에뮬레이션할 수 있는 128비트 십진수 기반 부동 소수점 값을 사용하는 BSON 데이터 유형 입니다. 이 기능은 금융 및 세금 계산과 같은 화폐 데이터 를 처리하는 애플리케이션을 위한 것입니다.

다음 예제에서는 inventory 컬렉션의 price 필드에 Decimal128 유형의 값을 삽입합니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
price = BSON::Decimal128.new("428.79")
client[:inventory].insert_one({ "_id" => 1,
"item" => "26 inch monitor",
"price" => price })

위 작업을 수행하면 다음 문서가 생성됩니다.

{ "_id" : 1, "item" : "26 inch monitor", "price" : NumberDecimal("428.79") }

Ruby BigDecimal 객체 또는 Decimal128.from_string() 를 사용하여 Decimal128 객체를 만들 수도 있습니다.

big_decimal = BigDecimal.new(428.79, 5)
price = BSON::Decimal128.new(big_decimal)
# => BSON::Decimal128('428.79')
price = BSON::Decimal128.from_string("428.79")
# => BSON::Decimal128('428.79')

Ruby 드라이버는 쿼리 캐시를 제공합니다. 쿼리 캐시를 활성화하면 찾기 및 집계 쿼리 결과를 저장하고 동일한 쿼리를 다시 수행할 때 저장된 결과를 반환합니다.

쿼리 캐시에 대해 자세히 알아보려면 쿼리 캐시 튜토리얼을 참조하세요.

Ruby 드라이버는 collection에서 find 메서드를 사용하는 쿼리에 유창한 인터페이스를 제공합니다. find 메서드에는 다양한 옵션을 사용할 수 있습니다.

결과를 반복할 때만 서버에 대해 쿼리가 느리게 실행되며, 이 시점에서 쿼리가 전달되고 Mongo::Cursor 이 반환됩니다.

지정된 필터에 대한 모든 문서를 찾으려면 쿼리와 함께 find 을 호출합니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].find(:name => 'Flying Lotus').each do |document|
#=> Yields a BSON::Document.
end

중첩된 문서를 쿼리하려면 점 표기법을 사용하여 중첩된 순서로 키를 지정합니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].find("records.releaseYear": 2008).each do |document|
#=> Yields a BSON::Document.
end

이 사용법은 더 이상 사용되지 않습니다.

find 메서드에서는 첫 번째 매개변수에 레거시 $query 구문을 사용하여 쿼리 및 옵션을 제공할 수 있습니다.

collection.find(:'$query' => {name: 'Mr. Smith'})
# Equivalent to:
collection.find(name: 'Mr. Smith')
collection.find(:'$query' => {name: 'Mr. Smith'}, :'$sort' => {age: 1})
# Equivalent to:
collection.find(name: 'Mr. Smith').sort(age: 1)

MongoDB 3.2 이상에 대해 쿼리가 실행되면 드라이버는 해당 서버 버전에 적합한 프로토콜을 사용하여 필요에 따라 쿼리를 찾기 명령 또는 OP_MSG 페이로드로 자동 변환합니다.

쿼리에 옵션을 추가하려면 find 메서드 뒤에 적절한 메서드를 연결합니다. 기본 객체인 Mongo::Collection::View 은(는) 변경할 수 없으며 각 메서드 호출 후에 새 객체가 반환됩니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
documents = client[:artists].find(:name => 'Flying Lotus').skip(10).limit(10)
documents.each do |document|
#=> Yields a BSON::Document.
end

다음은 쿼리할 때 추가할 수 있는 옵션과 해당 메서드의 예제의 전체 목록입니다.

옵션
설명
allow_disk_use
true로 설정하면 서버는 찾기 작업을 실행하는 동안 임시 데이터를 디스크에 쓸 수 있습니다. 이 옵션은 MongoDB Server 버전 4.4 이상에서만 사용할 수 있습니다.
allow_partial_results
샤드 cluster와 함께 사용합니다. 샤드가 다운된 경우 쿼리가 가동 중인 샤드에서 결과를 반환할 수 있도록 허용하여 잠재적으로 결과의 일부만 가져오도록 합니다.
batch_size(Integer)
GETMORE 작업에서 커서가 반환할 각 문서 배치의 크기를 지정합니다.
comment(String)
쿼리에 댓글을 추가합니다.
explain(**opts)

쿼리에 대한 쿼리 계획을 반환합니다. 기호 키를 사용하여 키워드 인수를 통해 설명 옵션 을 전달합니다.

# All server versions - default explain behavior
client[:artists].find.explain
# MongoDB 3.0 and newer
client[:artists].find.explain(verbosity: :query_planner)
client[:artists].find.explain(verbosity: :execution_stats)
client[:artists].find.explain(verbosity: :all_plans_execution)
# Alternative syntax using camel case
client[:artists].find.explain(verbosity: "queryPlanner")
client[:artists].find.explain(verbosity: "executionStats")
client[:artists].find.explain(verbosity: "allPlansExecution")
# MongoDB 2.6
client[:artists].find.explain(verbose: true)

설명 작업은 :session:read (읽기 설정 (read preference)의 경우) 옵션을 지원합니다. 단일 설명 작업에 이러한 옵션을 지정하려면 다음과 같이 find 메서드에 지정해야 합니다.

client[:artists].find({}, session: session).explain
client[:artists].find({}, read: {mode: :secondary_preferred}).explain

클라이언트나 collection에 읽기 설정 (read preference) 옵션이 지정된 경우 해당 옵션이 explain 작업으로 전달됩니다.

client[:artists, read: {mode: :secondary_preferred}].find.explain

collection 객체를 생성할 때는 세션 옵션이 허용되지 않습니다.

explain 명령은 읽기 고려 (read concern) 옵션 전달을 지원하지 않습니다. 클라이언트 또는 collection 수준에서 읽기 고려 (read concern)가 지정되어 있거나 읽기 고려 (read concern)가 찾기 옵션으로 지정된 경우 드라이버에서 설명 명령으로 읽기 고려 (read concern)를 전달하지 않습니다.

참고

서버가 explain 명령에 대해 반환하는 정보는 서버 버전 및 배포 토폴로지에 따라 다릅니다. 드라이버의 explain 메서드는 서버가 제공한 모든 것을 반환합니다.

``explain`` 메서드의 반환 값은 드라이버의 공개 API의 일부가 아니며 서버 버전 및 배포 토폴로지에 따라 달라집니다.

hint(Hash)
사용할 인덱스 힌트 를 쿼리에 제공합니다.
let(Hash)
쿼리에 사용할 변수 를 매핑합니다.
limit(Integer)
반환된 문서 수를 제공된 값으로 제한합니다.
max_scan(Integer)
전체 collection 스캔을 수행하는 경우 스캔할 최대 문서 수를 설정합니다. MongoDB Server 버전 4.0부터 더 이상 사용되지 않습니다.
max_time_ms(Integer)
쿼리 실행을 허용하는 최대 시간(밀리초)입니다.
no_cursor_timeout
MongoDB는 10분 후에 비활성 커서를 자동으로 닫습니다. 서버에서 커서를 무기한 열린 상태로 유지하려면 이를 호출합니다.
projection(Hash)

결과에 포함하거나 제외할 필드를 지정합니다.

client[:artists].find.projection(:name => 1)
read(Hash)

이 쿼리에 대한 읽기 설정 (read preference)만 변경합니다.

client[:artists].find.read(:mode => :secondary_preferred)
session(Session)
사용할 세션입니다.
show_disk_loc(Boolean)
디스크에 있는 문서의 위치도 포함하도록 결과에 지시합니다.
skip(Integer)
결과에서 제공된 수의 문서를 건너뜁니다.
snapshot
스냅샷 모드에서 쿼리를 실행합니다. MongoDB Server 버전 4.0부터 더 이상 사용되지 않습니다.
sort(Hash)

쿼리에 대한 정렬 기준을 지정합니다.

client[:artists].find.sort(:name => -1)
count_documents
필터와 일치하는 문서의 총 개수 또는 컬렉션 내 문서의 총 개수를 구하세요.
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].find(:name => 'Flying Lotus').count_documents
estimated_document_count

collection의 대략적인 문서 수를 구합니다.

과 달리 count_documents estimated_document_count 은 필터를 허용하지 않습니다.

count 서버 명령은 estimated_document_count 를 구현하는 데 사용됩니다. 자세한 내용은 Count: Behavior 를 통해 확인할 수 있습니다.

MongoDB 버전 5.0.0-5.0.7의 실수로 인해, estimated_document_count 가 구현에 사용하는 count 명령이 Stable API v1에 포함되지 않았습니다. 따라서 estimated_document_count 이(가) 포함된 Stable API 사용자는 서버 버전을 5.0.8 이상으로 업그레이드하거나 api_strict: false 을(를) 설정하여 오류가 발생하지 않도록 하는 것이 좋습니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].estimated_document_count
count

필터와 일치하는 문서의 대략적인 수 또는 collection의 대략적인 문서 수를 구하세요.

사용 중단: count 메서드는 더 이상 사용되지 않으며 트랜잭션에서 작동하지 않습니다. 필터와 일치할 가능성이 있는 문서의 정확한 수를 구하려면 count_documents 을 사용하고, collection의 대략적인 문서 수를 구하려면 estimated_document_count 를 사용하세요.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].find(:name => 'Flying Lotus').count
distinct
중복 값이 있는 문서를 필터링합니다. SQL distinct 절과 동일합니다.
client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].find.distinct(:name )

고정 사이즈 컬렉션의 경우 클라이언트가 초기 커서의 결과를 모두 사용한 후에도 계속 열려 있는 테일 커서( tailable cursor) 를 사용할 수 있습니다. 다음 코드 예제는 테일 커서(tailable cursor)를 사용하는 방법을 보여줍니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
client[:artists].drop
client[:artists, capped: true, size: 512].create
result = client[:artists].insert_many([
{ :name => 'Flying Lotus' },
{ :name => 'Aphex Twin' }
])
enum = client[:artists].find({}, cursor_type: :tailable_await).to_enum
while true
doc = enum.next
# do something
sleep(1)
end

읽기 고려 (read concern) 는 클라이언트 또는 collection에서 설정할 수 있습니다.

client = Mongo::Client.new(['localhost:14420'], database: 'music',
read_concern: {level: :local})
client['collection'].find.to_a
collection = client['collection', read_concern: {level: :majority}]
collection.find.to_a

이 드라이버는 현재 개별 쿼리에 대한 읽기 고려 (read concern) 설정을 지원하지 않습니다.

트랜잭션을 시작할 때 읽기 고려를 지정할 수 있습니다. 트랜잭션이 활성화되면 클라이언트 또는 컬렉션에 지정된 읽기 고려가 무시됩니다.

일반 명령 헬퍼를 사용할 때 읽기 고려 (read concern)를 명령의 일부로 지정할 수 있습니다.

client.database.command(dbStats: 1, readConcern: {level: :majority})

읽기 설정은 쿼리 또는 명령을 전송할 수 있는 후보 복제본 세트 멤버를 결정합니다. 이는 기호로 지정된 모드 , tag_sets 로 알려진 해시 배열, 헤지된 읽기 동작을 지정하는 해시인 hedge 옵션, 두 가지 타이밍 옵션 local_thresholdserver_selection_timeout 으로 구성됩니다.

local_threshold
가장 가까운 서버와 작업을 전송할 수 있는 적합한 서버 간의 지연 시간 창의 상한을 초 단위로 정의합니다. 기본값은 15밀리초 또는 0.015초입니다.
server_selection_timeout
예외가 발생하기 전에 서버 선택을 차단할 시간을 정의합니다. 기본값은 30,000밀리초 또는 30초입니다.

참고

읽기 설정 (read preference)은 독립형 배포에는 적용되지 않습니다. 클라이언트가 독립형 배포에 연결되면 애플리케이션에 지정된 모든 읽기 설정 (read preference)이 무시됩니다.

서버 선택에 사용되는 알고리즘에 대한 자세한 내용 은 GitHub 에서 서버 선택 문서 를 참조하세요. .

읽기 설정 (read preference)은 클라이언트에서 옵션으로 설정하거나 데이터베이스에서 명령이 실행될 때 옵션을 전달할 수 있습니다.

# Set read preference on a client, used for all operations
client = Mongo::Client.new([ '127.0.0.1:27017' ],
read: { mode: :secondary,
tag_sets: [ { 'dc' => 'nyc' } ]
} )
# Set read preference for a given command
client.database.command( { dbStats: 1 }, read: { mode: secondary,
tag_sets: [ { 'dc' => 'nyc' } ] } )

with 메서드를 사용하여 collection의 특정 작업에 대한 읽기 설정 (read preference)을 지정할 수도 있습니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
artists.with(:read => { :mode => :primary_preferred }).find.to_a

읽기 설정 모드에는 :primary, :secondary, :primary_preferred, :secondary_preferred 및 ``:nearest``의 다섯 가지가 있습니다. 모드에 대한 설명은 MongoDB 매뉴얼의 읽기 설정 문서를 참조하세요.

참고

클라이언트가 :direct_connection Ruby 옵션 또는 directConnection URI 옵션을 사용하여 서버에 직접 연결된 경우 읽기 설정 (read preference) 모드가 자동으로 :primary_preferred 로 설정되어 세컨더리에 대한 읽기 작업을 허용합니다. 애플리케이션이 :primary 읽기 설정 (read preference) 모드를 지정한 경우 모드는 자동으로 :primary_preferred 로 변환됩니다. 다른 읽기 설정 (read preference) 모드가 지정되면 변경되지 않고 서버로 전달됩니다.

tag_sets 매개변수는 데이터 센터 인식과 같이 서버 선택의 자격을 제한하는 데 사용되는 태그 세트의 정렬된 목록입니다. 태그 세트에 대한 설명은 MongoDB 매뉴얼의 읽기 설정 문서를 참조하세요.

읽기 설정 (read preference) 태그 세트(T)는 서버 태그 세트(S)와 일치하거나, 또는 T가 S의 하위 집합인 경우 서버 태그 세트(S)가 읽기 설정 (read preference) 태그 세트(T)와 일치합니다.

예를 들어 읽기 설정 태그 세트 { dc: 'ny', rack: 2 } 는 태그 세트 { dc: 'ny', rack: 2, size: 'large' } 의 세컨더리 서버와 일치합니다.

빈 태그 세트는 모든 태그 세트의 하위 집합이기 때문에 빈 문서인 태그 세트는 모든 서버와 일치합니다. 이는 기본 tag_sets 매개 변수 [{}] 이(가) 모든 서버와 일치함을 의미합니다.

hedge 매개변수는 서버가 헤지된 읽기(hedged read)를 사용해야 하는지 여부를 지정하는 해시입니다. 헤지된 읽기(hedged read)를 사용하면 샤드 cluster는 읽기 작업을 두 개의 복제본 세트 멤버로 라우팅하고 첫 번째 응답자로부터 결과를 반환할 수 있습니다.

hedge 옵션은 프라이머리가 아닌 읽기 설정 (read preference)에서만 지정할 수 있습니다. 이는 enabled 키가 true 또는 false 로 설정된 해시로 제공되어야 합니다.

client = Mongo::Client.new(
[ '127.0.0.1:27017' ],
read: { mode: :secondary, hedge: { enabled: true } },
)

헤지된 읽기(hedged read)에 대한 자세한 내용은 MongoDB 매뉴얼 을 참조하세요.

참고

hedge 옵션은 MongoDB Server 버전 4.4 이상에서만 사용할 수 있습니다. 이전 서버 버전에서 이 옵션을 사용하려고 하면 오류가 발생합니다.

문서 업데이트는 단일 또는 다중 업데이트를 실행하거나 $findAndModify 명령을 사용하여 가능합니다.

update_one

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
result = artists.find(:name => 'Goldie').update_one("$inc" => { :plays => 1 } )
result.n # Returns 1.
result = artists.update_one( { :name => 'Goldie' }, { "$inc" => { :plays => 1 } } )
result.n # Returns 1.

update_many

result = artists.find(:label => 'Hospital').update_many( "$inc" => { :plays => 1 } )
result.modified_count # Returns the number of documents that were updated.
result = artists.update_many( { :label => 'Hospital' }, { "$inc" => { :plays => 1 } } )
result.modified_count # Returns the number of documents that were updated.

replace_one

result = artists.find(:name => 'Aphex Twin').replace_one(:name => 'Richard James')
result.modified_count # Returns 1.
result = artists.replace_one( { :name => 'Aphex Twin' }, { :name => 'Richard James' } )
result.modified_count # Returns 1.

문서를 업데이트하고 $findAndModify 을 통해 문서를 반환하려면 제공된 세 가지 헬퍼 find_one_and_delete, find_one_and_replace 또는 find_one_and_update 중 하나를 사용합니다. 수정이 발생하기 전이나 후에 문서를 반환하도록 선택할 수 있습니다.

find_one_and_delete

client = Mongo::Client.new( [ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
artists.find(:name => 'José James').find_one_and_delete # Returns the document.

find_one_and_replace

doc = artists.find(:name => 'José James').find_one_and_replace(:name => 'José')
doc # Return the document before the update.
doc = artists.find_one_and_replace({ :name => 'José James' }, { :name => 'José' })
doc # Return the document before the update.
doc = artists.find(:name => 'José James').
find_one_and_replace( { :name => 'José' }, :return_document => :after )
doc # Return the document after the update.

find_one_and_update

doc = artists.find(:name => 'José James').
find_one_and_update( '$set' => { :name => 'José' } )
doc # Return the document before the update.
doc = artists.find_one_and_update( { :name => 'José James' }, { '$set' => { :name => 'José' } } )
doc # Return the document before the update.

업데이트 명령에 옵션을 추가하려면 옵션 해시 인수에 키-값 쌍으로 지정합니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
artists.indexes.create_one(name: 1)
# Force the server to use the name index to perform this operation
result = artists.update_one(
{ :name => 'Goldie' },
{ "$inc" => { :plays => 1 } },
{ hint: { name: 1 } }
)
result.n # Returns 1.

다음은 update_one, update_many, replace_one, find_one_and_delete, find_one_and_updatefind_one_and_replace 를 포함한 업데이트 작업에 추가할 수 있는 옵션 목록입니다.

옵션
설명
array_filters
필터 문서의 배열로, 배열 필드에 대한 업데이트 작업을 위해 수정할 배열 요소를 결정합니다.
bypass_document_validation
문서를 작성하기 전에 문서 수준 유효성 검사를 건너뛸지 여부입니다.
collation
특정 언어의 규칙을 준수하는 문자열을 비교할 때 사용할 규칙 세트를 지정합니다.
hint
이 작업에 사용할 인덱스입니다. 해시(예: { _id: 1 }) 또는 문자열(예: "_id_"). MongoDB Server 버전 4.2 이상에서 update_one, update_manyreplace_one 명령에 대해, 서버 버전 4.4 이상에서 find_one_and_delete, find_one_and_updatefind_one_and_replace 명령에 대해 지원됩니다.
let(Hash)
이 작업에 사용할 변수 매핑입니다.
projection
작업 결과에서 제외하거나 포함할 필드입니다( find_one_and_delete, find_one_and_replacefind_one_and_update 명령에서만 사용 가능).
return_document
업데이트된 문서를 업데이트 전의 상태로 반환할지, 아니면 이후의 상태로 반환할지를 지정하는 기호입니다. 잠재적인 값은 :before 또는 :after 입니다. ( find_one_and_updatefind_one_and_replace 명령에서만 사용 가능).
sort
찾기 및 수정 명령의 결과를 정렬하는 방법입니다. 해시 키-값 쌍으로 지정되며, 키는 정렬 기준으로 사용할 필드 이름이고 값은 1 또는 -1로 오름차순 또는 내림차순으로 정렬을 지정합니다( find_one_and_delete 에서만 사용 가능, find_one_and_replacefind_one_and_update 명령).
session
이 작업에 사용할 세션입니다.
upsert
문서가 존재하지 않는 경우 업서트할지 여부입니다. find_one_and_delete 작업에 사용할 수 없습니다.

업데이트 옵션에 대한 자세한 내용은 다음 명령에 대한 MongoDB Server 설명서를 참조하세요.

delete_one

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
result = artists.find(:name => 'Björk').delete_one
result.deleted_count # Returns 1.
result = artists.delete_one(:name => 'Björk')
result.deleted_count # Returns 1.

delete_many

result = artists.find(:label => 'Mute').delete_many
result.deleted_count # Returns the number deleted.
result = artists.delete_many(:label => 'Mute')
result.deleted_count # Returns the number deleted.

삭제 명령에 옵션을 추가하려면 옵션 해시 인수에 키-값 쌍으로 지정합니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'music')
artists = client[:artists]
artists.indexes.create_one(name: 1)
# Force the server to use the name index to perform this operation
result = artists.find(:name => 'Björk').delete_one(hint: { name: 1 })
result.deleted_count # Returns 1.

다음은 delete_onedelete_many 작업에 추가할 수 있는 사용 가능한 옵션의 전체 목록입니다.

옵션
설명
collation
특정 언어의 규칙을 준수하는 문자열을 비교할 때 사용할 규칙 세트를 지정합니다.
hint
이 작업에 사용할 인덱스입니다. 해시(예: { _id: 1 }) 또는 문자열(예: "_id_"). MongoDB Server 버전 4.4 이상에서 지원됩니다.
let(Hash)
이 작업에 사용할 변수 매핑입니다.
session
이 작업에 사용할 세션입니다.

업데이트 옵션에 대한 자세한 내용은 삭제 명령에 대한 MongoDB 서버 설명서를 참조하세요.

MongoDB의 모든 쓰기 작업은 특정 쓰기에 대해 MongoDB에서 요청한 승인 수준인 쓰기 고려로 실행됩니다. 일반적인 쓰기 고려에 대한 자세한 내용은 MongoDB 매뉴얼 에서 확인할 수 있습니다.

Ruby 드라이버는 클라이언트, collection, 세션(해당 세션의 트랜잭션), 트랜잭션, GridFS 버킷 및 쓰기 스트림 수준에 대한 쓰기 고려 (write concern) 지정은 물론 Database#command 를 통해 명령을 수동으로 실행할 때의 쓰기 고려 (write concern)를 지정할 수 있도록 지원합니다.

드라이버 버전 2.10부터 쓰기 고려 (write concern)를 허용하는 모든 객체는 :write_concern 옵션을 통해 쓰기 고려 (write concern)를 허용하며, 이 옵션에는 쓰기 고려 (write concern) 옵션과 함께 해시가 제공되어야 합니다. :write 옵션 사용은 더 이상 사용되지 않습니다. 드라이버 버전 2.9 이하에서 클라이언트, collection 및 GridFS 객체는 :write_concern 옵션을 사용하는 세션 및 트랜잭션 객체와 함께 :write 옵션에서 쓰기 고려 (write concern) 옵션을 취했습니다.

다음은 쓰기 고려 (write concern)를 클라이언트 및 collection 객체에 전달하는 몇 가지 예입니다. 새 클라이언트 및 collection 객체를 구성할 때 또는 #with 메서드에 :write_concern 옵션을 제공할 수 있습니다.

GridFS 예제는 GridFS 페이지에서 제공됩니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 2})
alt_client = client.with(write_concern: {w: :majority})
collection = client[:artists, write_concern: {w: 3}]
alt_collection = collection.with(write_concern: {w: :majority})
# Uses w: 3
collection.insert_one({name: 'SUN Project'})
# Uses w: :majority
alt_collection.insert_one({name: 'SUN Project'})

드라이버 버전 2.9 이하에서는 :write 옵션을 통해 클라이언트 및 collection 수준에서 쓰기 고려 (write concern)를 허용했습니다. 이 사용법은 이전 버전과의 호환성을 위해 계속 지원되지만 더 이상 사용되지 않습니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write: {w: 2})
alt_client = client.with(write: {w: :majority})
collection = client[:artists, write: {w: 3}]
alt_collection = collection.with(write: {w: :majority})

:write:write_concern 옵션이 모두 제공되는 경우 해당 값이 동일해야 하며 그렇지 않으면 예외가 발생합니다.

# OK
client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 3}, write: {w: 3})
# Error
client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 3}, write: {w: :majority})

클라이언트나 컬렉션의 옵션을 변경하는 데 #with 메서드를 사용하는 경우 이름이 다른 경우 마지막으로 제공된 옵션이 우선합니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 2})
alt_client = client.with(write: {w: 3})
alt_client.options[:write]
# => {"w"=>3}
alt_client.options[:write_concern]
# => nil

트랜잭션을 사용할 때 쓰기 commit_transaction abort_transaction 고려는 트랜잭션 사양 에 따라 및 작업을 통해서만 서버로 전송됩니다. .:write_concern 쓰기 with_transaction start_transaction 고려는 또는 default_transaction_options 호출의 옵션이나 세션 객체의 옵션을 통해 설정할 수 있습니다. 둘 다 설정되지 않은 경우 클라이언트의 쓰기 고려가 사용됩니다. 트랜잭션은 작업과 관련된 컬렉션의 쓰기 고려를 무시합니다. 쓰기 고려를 :write 트랜잭션 옵션으로 설정할 때 옵션은 모든 드라이버 버전에서 인식되지 않습니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 2})
collection = client[:artists, write_concern: {w: :majority}]
session = client.start_session
session.with_transaction do
collection.insert_one({test: 1}, session: session)
# Uses w: 2 when committing
end
session = client.start_session(default_transaction_options:
{write_concern: {w: 3})
)
session.with_transaction do
collection.insert_one({test: 1}, session: session)
# Uses w: 3 when committing
end
session = client.start_session
session.with_transaction(write_concern: {w: 3}) do
collection.insert_one({test: 1}, session: session)
# Uses w: 3 when committing
end

쓰기 고려 (write concern)가 상속되면 상속은 개별 요소가 아닌 전체 쓰기 고려 (write concern) 해시에 적용됩니다. 예를 들어 다음과 같은 경우 j: true 가 상속되지 않습니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 1, j: true})
collection = client[:artists, write_concern: {w: 2}]
collection.write_concern.options
# => #<Mongo::WriteConcern::Acknowledged:0x47289650367880 options={:w=>2}>

CRUD 작업은 옵션 해시를 허용하지만 현재는 :write_concern 옵션을 인식하지 못합니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], database: 'music',
write_concern: {w: 2})
collection = client[:artists, write_concern: {w: :majority}]
# Still uses w: :majority
collection.insert_one({name: 'SUN Project'}, write_concern: {w: 1})

이에 대한 가장 쉬운 해결 방법은 #with 를 사용하여 원하는 쓰기 고려 (write concern)가 있는 새 collection 인스턴스를 얻는 것입니다.

# Uses w: 1
collection.with(write_concern: {w: 1}).insert_one(name: 'SUN Project')

쓰기 고려 (write concern)는 Database#command에서 수동으로 지정할 수도 있습니다.

client.database.command(create: 'foo-collection', writeConcern: {w: :majority})

여기서 writeConcern은 옵션이 아니라 작업의 일부이며 구문은 Ruby 드라이버가 사용하는 밑줄이 아닌 MongoDB Server가 인식하는 구문입니다.

Mongo Ruby 드라이버 버전 2 부터 시작됩니다.18.0 부터는 달러 기호($)로 시작하는 필드와 마침표(.)가 있는 필드로 작업할 수 있습니다. 드라이버 버전 2.17.0 및 이전 버전에서는 점 또는 달러 필드로 작업하려고 하면 IllegalKey 오류가 발생합니다. 이러한 유형의 필드를 사용하는 방법에 대한 자세한 내용 은 마침표(.) 및 달러 기호($)가 있는 필드 이름 에 대한 MongoDB 문서를 참조하세요.

BSON 사양에서는 BSON 기호 유형이 더 이상 사용되지 않기 때문에 bson gem은 독립적으로 사용될 때 Ruby 기호를 BSON 문자열로 직렬화합니다. 그러나 이전 데이터 세트와의 호환성을 유지하기 위해 Ruby 드라이버는 이 동작을 재정의하여 Ruby 기호를 BSON 기호로 직렬화합니다. 이는 BSON 기호를 필드로 포함하는 문서에 대한 쿼리를 지정하는 데 필요합니다. 그럼에도 불구하고 기호 유형 필드가 있는 새 문서는 데이터베이스에 저장해서는 됩니다. 대신 문자열 필드를 사용하세요.

기본 동작을 재정의하고 기호 값을 문자열로 인코딩하도록 드라이버를 구성하려면 프로젝트에 다음 코드 스니펫을 포함하세요.

class Symbol
def bson_type
BSON::String::BSON_TYPE
end
end
← 데이터와 함께 작업하기