개요
이 가이드에서는 Rust 드라이버를 사용하여 MongoDB 데이터베이스 및 collection에 액세스하고 managed 방법을 배울 수 있습니다.
MongoDB는 데이터를 계층적 구조로 구성합니다. MongoDB 배포서버에는 하나 이상의 데이터베이스 가 포함되며, 각 데이터베이스에는 하나 이상의 collection 이 포함됩니다. 각 collection에서 MongoDB는 필드 및 값 쌍을 포함하는 문서 로 데이터를 저장합니다.
문서 데이터 형식에 대해 자세히 알아보려면 MongoDB Server 매뉴얼에서 문서 를 참조하세요.
데이터베이스에 액세스
You can access a database by retrieving a Database instance from your client. You can use a Database
instance to perform database-level operations and access collections that the database contains.
Call one of the following methods on a Client instance to create a Database
:
database(): retrieve a database by its name
database_with_options(): set options (DatabaseOptions) while retrieving a database by its name
default_database(): access the default database specified for your
Client
instance
팁
클라이언트의 기본 데이터베이스를 지정하려면 ClientOptions
구조체의 default_database
필드를 설정합니다. 이 필드를 설정하지 않으면 드라이버는 연결 문자열의 defaultauthdb
구성 요소에서 기본 데이터베이스를 가져옵니다.
존재하지 않는 데이터베이스의 이름을 database()
또는 database_with_options()
메서드에 전달하면 드라이버는 여전히 Database
인스턴스를 반환합니다. 이 데이터베이스의 collection에 데이터를 삽입하면 서버가 해당 데이터를 생성합니다.
다음 예에서는 database()
메서드를 사용하여 test_db
데이터베이스에 액세스합니다.
let db = client.database("test_db");
목록 데이터베이스
To see a list of your deployment's databases, call the list_database_names() method on your Client
instance. This method returns a Vec<String>
type, a vector containing the database names as strings.
To see detailed information about each database, call the list_databases() method on your Client
instance. This method returns a Vec<DatabaseSpecification>
type. The DatabaseSpecification type contains fields describing each database, such as its size and whether it contains data.
다음 예에서는 list_database_names()
메서드를 사용하여 데이터베이스 목록을 인쇄하는 방법을 보여 줍니다.
let db_list = client.list_database_names().await?; println!("{:?}", db_list);
["admin", "local", "test_db", ...]
데이터베이스 제거
Dropping a database permanently deletes all the data in that database's collections. To drop a database, call the drop() method on your Database
instance. The following code shows how to drop a database referenced by the db
variable:
db.drop().await?;
경고
데이터베이스를 삭제하면 데이터가 삭제됩니다.
데이터베이스를 삭제하면 데이터베이스의 모든 collection의 모든 문서와 해당 collection의 모든 인덱스가 영구적으로 삭제됩니다. 데이터베이스를 삭제한 후에는 해당 데이터에 액세스하거나 복원할 수 없습니다.
컬렉션에 액세스
You can access a collection by retrieving a Collection instance from your database. You can use a Collection
instance to perform data operations, create aggregations, and manage indexes. Call one of the following methods on a Database
instance to retrieve a Collection
:
collection(): retrieve a collection by its name
collection_with_options(): set options (CollectionOptions) while accessing a collection by its name
존재하지 않는 컬렉션 의 이름을 collection()
또는 collection_with_options()
메서드에 전달하면 운전자 는 여전히 Collection
인스턴스 반환합니다. 이 컬렉션 에 데이터를 삽입하면 서버 에서 데이터를 생성합니다. 컬렉션 을 명시적으로 만드는 방법을 학습 보려면 이 가이드 의 컬렉션 만들기 섹션을 참조하세요.
이 예에서는 collection_with_options()
메서드를 사용하여 다음 조치를 수행합니다.
변수가 참고하는
coll_xyz
데이터베이스에서 collection에 액세스합니다.db
컬렉션에 대한 쓰기 기본 설정을
CollectionOptions
유형으로 설정합니다.
let wc = WriteConcern::builder().journal(true).build(); let coll_opts = CollectionOptions::builder().write_concern(wc).build(); let my_coll: Collection<Document> = db.collection_with_options("coll_xyz", coll_opts);
쓰기 고려에 대해 자세히 알아보려면 MongoDB Server 매뉴얼에서 쓰기 고려를 참조하세요.
collection 매개변수화
collection의 데이터를 직렬화할 데이터 유형을 지정하여 Collection
인스턴스를 매개변수화해야 합니다. 특정 유형으로 매개변수화된 Collection
인스턴스에서 메서드를 호출하면 메서드는 이 유형의 인스턴스를 허용하거나 반환합니다.
참고
Collection
인스턴스를 매개변수화하지 않으면 동일한 범위에서 지정된 데이터 유형을 사용하여 CRUD 작업을 수행할 때 컴파일러가 일반 유형을 유추합니다.
다음 예시에서는 Document
유형으로 collection을 매개변수화하는 동일한 방법을 보여줍니다.
let my_coll: Collection<Document> = client.database("test_db").collection("coll_xyz"); let my_coll = client.database("test_db").collection::<Document>("coll_xyz");
팁
Document
유형 대신 데이터를 모델링하는 사용자 지정 유형으로 Collection
인스턴스를 매개변수화하는 것이 좋습니다. 특정 데이터를 모델링하는 유형을 정의하여 반복적인 직렬화 및 유효성 검사를 방지할 수 있습니다.
Rust 운전자 의 직렬화에 학습 보려면 데이터 모델링 및 직렬화가이드 를 참조하세요.
컬렉션 생성
You can explicitly create a collection by calling the create_collection() method on a Database
instance. This method takes the collection name as a parameter. You can use a Collection
instance to perform data operations, create aggregations, and manage indexes.
다음 코드는 db
변수가 참조하는 데이터베이스 내에서 coll_abc
컬렉션을 생성하는 방법을 보여줍니다.
db.create_collection("coll_abc").await?;
collection을 만들 때 스키마 유효성 검사를 구현하여 문서 스키마를 일관되게 유지하고 쓰기 작업이 유효성 검사 규칙을 우회할 수 있는지 여부를 제어할 수 있습니다. 이 기능을 활성화하는 방법을 알아보려면 스키마 유효성 검사 가이드를 참조하세요.
listCollections (영문)
To see the names of the collections in a database, call the list_collection_names() method on your Database
instance. This method returns a Vec<String>
type, a vector containing the collection names as strings.
To see detailed information about each collection, call the list_collections() method on your Database
instance. This method returns a Vec<CollectionSpecification>
type. The CollectionSpecification type contains fields describing each collection, such as its type and settings.
다음 예에서는 list_collection_names()
메서드를 사용하여 db
변수가 참고하는 데이터베이스의 collection 이름을 출력하는 방법을 보여 줍니다:
let coll_list = db.list_collection_names().await?; println!("{:?}", coll_list);
["my_coll", "coll_xyz", ...]
제거 collection
Dropping a collection permanently deletes all the data in that collection. To drop a collection, call the drop() method on your Collection
instance. The following code shows how to drop a collection referenced by the my_coll
variable:
my_coll.drop().await?;
경고
collection을 삭제하면 데이터가 삭제됩니다.
데이터베이스에서 컬렉션을 삭제하면 해당 컬렉션 내의 모든 문서와 해당 컬렉션의 모든 인덱스가 영구적으로 삭제됩니다. collection을 삭제한 후에는 collection의 데이터에 액세스하거나 복원할 수 없습니다.
추가 정보
이 가이드의 개념에 대한 자세한 내용은 다음 문서를 참조하세요.
문서 삽입 가이드
MongoDB Server 매뉴얼의 데이터베이스 및 컬렉션
MongoDB Server 매뉴얼의 문서