개요
이 가이드에서는 읽기 작업 을 사용하여 MongoDB collection에서 데이터를 검색하는 방법에 대해 설명합니다. 읽기 작업은 서버에서 문서를 검색하는 명령입니다.
읽기 작업에는 두 가지 유형이 있습니다.
collection에서 문서를 검색할 수 있는 찾기 작업
collection의 데이터를 변환할 수 있는 애그리게이션 작업
이 가이드에는 다음 섹션이 포함되어 있습니다.
예시용 샘플 데이터
이 가이드의 예에서는 다음 샘플 문서를 사용합니다. 각 문서는 매장 재고에 있는 품목을 나타내며 분류 및 단가에 대한 정보를 포함합니다.
let docs = vec! [ Inventory { item: "candle".to_string(), category: "decor".to_string(), unit_price: 2.89, }, Inventory { item: "blender".to_string(), category: "kitchen".to_string(), unit_price: 38.49, }, Inventory { item: "placemat".to_string(), category: "kitchen".to_string(), unit_price: 3.19, }, Inventory { item: "watering can".to_string(), category: "garden".to_string(), unit_price: 11.99, } ];
작업 찾기
찾기 작업을 사용하여 MongoDB에서 데이터를 검색합니다. 찾기 작업은 find() 및 find_one() 메서드로 구성됩니다.
일치하는 모든 문서 찾기
기준과 일치 하는 모든 문서 를 찾으려면 find() 메서드를 사용합니다. 이 메서드는 쿼리 필터를 매개 변수로 사용합니다. 쿼리 필터는 문서가 일치시킬 기준을 형성하는 필드와 값으로 구성됩니다.
이 메서드는 필터 기준과 일치하는 문서를 검색하기 위해 반복할 수 있는 Cursor 유형을 반환합니다.
이 메서드를 사용하여 데이터를 검색하는 예제를 보려면 find() 예제를 참조하세요.
쿼리 지정에 학습 보려면 쿼리 지정 가이드 를 참조하세요.
하나의 문서 찾기
기준과 일치 하는 첫 번째 문서 를 찾으려면 find_one() 메서드를 사용합니다. 이 메서드는 쿼리 필터를 매개 변수로 사용합니다. 쿼리 필터는 문서가 일치시킬 기준을 형성하는 필드와 값으로 구성됩니다.
문서가 필터 기준과 일치하면 메서드는 값이 Some 인 Result<Option<T>> 유형을 반환합니다. 필터 기준과 일치하는 문서가 없는 경우 find_one() 는 값이 None 인 Result<Option<T>> 유형을 반환합니다.
이 메서드를 사용하여 데이터를 조회 하는 예시 를 보려면 find_one() 예시 를 참조하세요.
검색 동작 수정
FindOptions 인스턴스를 매개 변수로 전달하여 find() 의 동작을 수정하고 FindOneOptions 인스턴스를 전달하여 find_one() 의 동작을 수정할 수 있습니다.
각 설정에 기본값을 사용하려면 None 값을 옵션 매개 변수로 지정합니다.
다음 표에서는 FindOptions 및 FindOneOptions 에서 지정할 수 있는 일반적으로 사용되는 설정을 설명합니다.
설정 | 설명 |
|---|---|
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: CollationDefault: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. Type: HintDefault: None |
| The projection to use when returning results. Type: DocumentDefault: None |
| The read concern to use for the find operation. If you don't
set this option, the operation inherits the read concern set for the
collection. To learn more about read concerns, see
Read Concern
in the Server manual. Type: ReadConcern |
| The number of documents to skip when returning results. To learn more
about how to use the skip() builder method, see Skip Returned Results.Type: u64Default: None |
| The sort to use when returning results. By default, the driver
returns documents in their natural order, or as they appear in
the database. To learn more, see natural order
in the Server manual glossary. To learn more about how to use the
sort() builder method, see Sort Results.Type: DocumentDefault: None |
참고
인스턴스화 옵션
Rust 드라이버는 FindOneOptions 또는 FindOptions 와 같은 다양한 유형을 생성하기 위해 빌더 디자인 패턴을 구현합니다. 각 유형의 builder() 메서드를 사용하여 옵션 빌더 함수를 한 번에 하나씩 연결하여 옵션 인스턴스를 구성할 수 있습니다.
각 유형에 대해 지정할 수 있는 설정의 전체 목록은 FindOptions 및 FindOneOptions에 대한 API 설명서를 참조하세요.
예시
다음 섹션에는 find() 및 findOne() 메서드를 사용하여 필터 기준과 일치하는 샘플 문서를 조회하는 예가 포함되어 있습니다.
find() 예제
이 예에서는 다음 매개 변수를 사용하여 find() 메서드를 호출하는 방법을 보여 줍니다.
값이
unit_price보다 작고 이 아닌 문서와 일치하는 쿼리 필터입니다.12.00category"kitchen"일치하는 문서를
unit_price기준으로 내림차순으로 정렬하는FindOptions인스턴스
let opts = FindOptions::builder() .sort(doc! { "unit_price": -1 }) .build(); let mut cursor = my_coll.find( doc! { "$and": vec! [ doc! { "unit_price": doc! { "$lt": 12.00 } }, doc! { "category": doc! { "$ne": "kitchen" } } ] }, opts ).await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); };
Inventory { item: "watering can", category: "garden", unit_price: 11.99 } Inventory { item: "candle", category: "decor", unit_price: 2.89 }
find_one() 예제
이 예에서는 다음 매개 변수를 사용하여 find_one() 메서드를 호출하는 방법을 보여 줍니다.
unit_price값이20.00보다 작거나 같은 문서를 일치시키는 쿼리 필터일치하는 처음 두 문서를 건너뛰는
FindOneOptions인스턴스
let opts = FindOneOptions::builder().skip(2).build(); let result = my_coll.find_one( doc! { "unit_price": doc! { "$lte": 20.00 } }, opts ).await?; println!("{:#?}", result);
Some( Inventory { item: "watering can", category: "garden", unit_price: 11.99, }, )
집계 작업
애그리게이션 작업을 사용하여 collection에서 데이터를 검색하고 변환합니다. aggregate() 메서드를 사용하여 애그리게이션 작업을 수행할 수 있습니다.
문서 데이터 집계
aggregate() 메서드는 집계 파이프라인 을 매개 변수로 사용합니다. 집계 파이프라인에는 데이터를 변환하는 방법을 지정하는 하나 이상의 단계 가 포함됩니다. 단계에는 애그리게이션 연산자(접두사 $)와 해당 연산자에 대한 필수 매개변수가 포함됩니다.
애그리게이션에 대해 자세히 알아보고 애그리게이션 예제를 보려면 애그리 게이션 가이드를 참조하세요.
이 메서드는 결과 문서를 Cursor 유형으로 반환합니다. 집계 파이프라인에 $match 단계가 포함되어 있지 않은 경우 파이프라인은 컬렉션의 모든 문서를 처리합니다.
애그리게이션 동작 수정
AggregateOptions 인스턴스를 선택적 매개변수로 전달하여 aggregate() 의 동작을 수정할 수 있습니다.
각 설정에 기본값을 사용하려면 None 값을 옵션 매개 변수로 지정합니다.
다음 표에서는 AggregateOptions 에서 지정할 수 있는 일반적으로 사용되는 설정에 대해 설명합니다.
설정 | 설명 |
|---|---|
| Enables writing to temporary files. If true,
aggregation stages can write data to the _tmp subdirectory in the
dbPath directory.Type: boolDefault: false |
| Specifies the maximum number of documents the server returns per
cursor batch. This option sets the number of documents the cursor
keeps in memory rather than the number of documents the cursor
returns. Type: u32Default: 101 documents initially, 16 MB maximum for
subsequent batches |
| The collation to use when sorting results. To learn more about collations,
see the Collations guide. Type: CollationDefault: None |
| The index to use for the operation. To learn more about
indexes, see Indexes in the Server
manual. Type: HintDefault: None |
| The read concern to use for the find operation. If you don't
set this option, the operation inherits the read concern set for the
collection. To learn more about read concerns, see
Read Concern
in the Server manual. Type: ReadConcern |
| The write concern for the operation. If you don't set this
option, the operation inherits the write concern set for
the collection. To learn more about write concerns, see
Write Concern in the
Server manual. Type: WriteConcern |
전체 설정 목록은 AggregateOptions에 대한 API 설명서를 참조하세요.
예시
이 예시에서는 다음 단계가 포함된 파이프라인을 사용하여 aggregate() 메서드를 호출하는 방법을 보여 줍니다.
category필드별로 문서를 그룹화하고category별로unit_price필드의 평균을 계산하는$group단계$sort단계를avg_price별로 오름차순으로 정렬합니다.
let pipeline = vec![ doc! { "$group": doc! { "_id" : doc! {"category": "$category"} , "avg_price" : doc! { "$avg" : "$unit_price" } } }, doc! { "$sort": { "_id.avg_price" : 1 } } ]; let mut cursor = my_coll.aggregate(pipeline, None).await?; while let Some(result) = cursor.try_next().await? { println!("{:?}", result); };
Document({"_id": Document({"category": String("decor")}), "avg_price": Double(2.890000104904175)}) Document({"_id": Document({"category": String("kitchen")}), "avg_price": Double(20.840000867843628)}) Document({"_id": Document({"category": String("garden")}), "avg_price": Double(11.989999771118164)})
추가 정보
찾기 작업의 실행 가능한 예는 다음과 같은 사용의 예를 참조하세요.
이 가이드의 작업에 대해 자세히 알아보려면 다음 문서를 참조하세요.
애그리게이션 가이드
결과 정렬 가이드
반환된 결과 건너뛰기 가이드
반환된 결과 수 제한 가이드
API 문서
이 가이드에서 사용되는 메서드 또는 유형에 대해 자세히 알아보려면 다음 API 문서를 참조하세요.