문서 메뉴
문서 홈
/ / /
Ruby MongoDB Driver
/

Ruby 드라이버 빠른 시작

이 페이지의 내용

  • 전제 조건
  • 연결하기
  • 데이터베이스 및 컬렉션에 액세스하기
  • 문서 삽입
  • 컬렉션 쿼리하기
  • 문서 업데이트
  • 문서 삭제
  • 인덱스 만들기
  • 샘플 앱 완성하기
  • 기본 포트인 27017을 사용하여 localhost에서 실행 중인 MongoDB 인스턴스입니다.

  • Ruby MongoDB 드라이버. MongoDB 드라이버 설치 방법에 대한 지침은 설치를 참조하세요.

  • 코드 상단에 다음 문장을 추가합니다.

require 'mongo'

실행 중인 MongoDB 인스턴스에 대한 연결을 설정하려면 Mongo::Client를 사용합니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')

URI 연결 문자열을 사용할 수도 있습니다.

client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')

다음도 참조하세요.

다음 예시에서는 특정 데이터베이스에 액세스하고 해당 컬렉션을 표시하는 방법을 보여줍니다.

client = Mongo::Client.new([ '127.0.0.1:27017' ], :database => 'test')
db = client.database
db.collections # returns a list of collection objects
db.collection_names # returns a list of collection names
db.list_collections # returns a list of collection metadata hashes

컬렉션에 액세스하려면 이름으로 컬렉션을 참조합니다.

collection = client[:restaurants]

컬렉션이 존재하지 않으면 데이터를 처음 넣을 때 서버에서 컬렉션을 생성합니다.

컬렉션에 단일 문서를 삽입하려면 insert_one 메서드를 사용합니다.

client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
doc = {
name: 'Steve',
hobbies: [ 'hiking', 'tennis', 'fly fishing' ],
siblings: {
brothers: 0,
sisters: 1
}
}
result = collection.insert_one(doc)
result.n # returns 1, because one document was inserted

컬렉션에 여러 문서를 삽입하려면 insert_many 메서드를 사용합니다.

docs = [ { _id: 1, name: 'Steve',
hobbies: [ 'hiking', 'tennis', 'fly fishing' ],
siblings: { brothers: 0, sisters: 1 } },
{ _id: 2, name: 'Sally',
hobbies: ['skiing', 'stamp collecting' ],
siblings: { brothers: 1, sisters: 0 } } ]
result = collection.insert_many(docs)
result.inserted_count # returns 2 because two documents were inserted

find 메서드를 사용하여 컬렉션 쿼리를 생성합니다.

빈 쿼리 필터는 컬렉션의 모든 문서를 반환합니다.

client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
collection.find.each do |document|
#=> Yields a BSON::Document.
end

일치하는 문서만 찾으려면 쿼리 필터를 사용합니다.

client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
puts collection.find( { name: 'Sally' } ).first

이 예시에서는 다음을 출력합니다.

{"_id" => 2, "name" => "Sally", "hobbies" => ["skiing", "stamp collecting"], "siblings" => { "brothers": 1, "sisters": 0 } }

일치시키려는 키와 값을 지정하여 중첩된 문서를 쿼리합니다.

client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
puts collection.find("siblings.sisters": 1 ).first

이 예시에서는 다음을 출력합니다.

{"_id"=>1, "name"=>"Steve", "hobbies"=>["hiking", "tennis", "fly fishing"], "siblings"=>{"brothers"=>0, "sisters"=>1}}

다음도 참조하세요.

update_oneupdate_many를 포함하여 여러 업데이트 메서드가 있습니다. update_one은 단일 문서를 업데이트하고 update_many는 한 번에 여러 문서를 업데이트합니다.

두 메서드 모두 쿼리 필터 문서와 업데이트 데이터가 포함된 두 번째 문서를 인수로 사용합니다. 특정 필드(하나 또는 여러 개)를 추가하거나 업데이트하려면 $set를 사용합니다. $set가 없으면 전체 기존 문서가 업데이트 데이터로 대체됩니다.

client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
result = collection.update_one( { 'name' => 'Sally' }, { '$set' => { 'phone_number' => "555-555-5555" } } )
puts collection.find( { 'name' => 'Sally' } ).first

이 예시에서는 다음을 출력합니다.

{"_id" => 2, "name" => "Sally", "hobbies" => ["skiing", "stamp collecting"], "phone_number" => "555-555-5555"}

다음 예시에서는 빈 쿼리 필터와 함께 update_many를 사용하여 컬렉션의 모든 문서를 업데이트합니다.

client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
result = collection.update_many( {}, { '$set' => { 'age' => 36 } } )
puts result.modified_count # returns 2 because 2 documents were updated

다음도 참조하세요.

컬렉션에서 문서를 삭제하려면(한 번에 하나씩 또는 여러 개) delete_one 또는 delete_many 메서드를 사용합니다.

client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
result = collection.delete_one( { name: 'Steve' } )
puts result.deleted_count # returns 1 because one document was deleted

다음 예시에서는 컬렉션에 레코드 두 개를 더 삽입한 다음 정규식과 일치하는 name 필드가 있는 모든 문서를 삭제하여 'S'로 시작하는 문자열을 찾습니다.

client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
collection.insert_many([ { _id: 3, name: "Arnold" }, { _id: 4, name: "Susan" } ])
puts collection.count # counts all documents in collection
result = collection.delete_many({ name: /$S*/ })
puts result.deleted_count # returns the number of documents deleted

인덱스를 하나씩 생성하거나 한 번에 여러 개 생성하려면 create_one 또는 create_many 메서드를 사용합니다.

client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
collection.indexes.create_one({ name: 1 }, unique: true)

1개의 문으로 여러 인덱스를 만들려면 create_many 메서드를 사용합니다. create_many를 사용하는 경우 구문은 create_one과 다릅니다.

client = Mongo::Client.new('mongodb://127.0.0.1:27017/test')
collection = client[:people]
collection.indexes.create_many([
{ key: { name: 1 } , unique: true },
{ key: { hobbies: 1 } },
])

다음도 참조하세요.

몇 가지 일반적인 사용 사례에 Ruby 드라이버를 사용하는 샘플 앱은 GitHub 에서 다운로드할 수 있습니다. .

← 튜토리얼