개요
이 가이드에서는 읽기 작업 을 사용하여 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() 에 연결하여 find() 메서드의 동작을 수정하고 FindOneOptions 옵션 빌더 메서드를 find_one() 에 연결하여 find_one() 메서드의 동작을 수정할 수 있습니다.
다음 표에서는 해당 빌더 메서드를 호출하여 설정하다 수 있는 일반적으로 사용되는 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. To learn more about projections, see the Specify Fields to Return guide. 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.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.Type: DocumentDefault: None |
참고
설정 옵션
옵션 빌더 메서드를 찾기 작업 메서드 호출에 직접 연결하여 FindOptions 및 FindOneOptions 필드를 설정하다 수 있습니다. 이전 버전의 운전자 를 사용하는 경우 옵션 빌더 메서드를 builder() 메서드에 연결하여 FindOptions 또는 FindOneOptions 인스턴스 를 구성해야 합니다. 그런 다음 옵션 인스턴스 를 find() 또는 find_one() 에 매개 변수로 전달합니다.
각 유형에 대해 지정할 수 있는 설정의 전체 목록은 FindOptions 및 FindOneOptions에 대한 API 설명서를 참조하세요.
찾기 예시
다음 섹션에는 find() 및 find_one() 메서드를 사용하여 필터 기준과 일치하는 샘플 문서를 조회하는 예가 포함되어 있습니다.
find() 예제
이 예에서는 다음 조치를 수행합니다.
find()메서드 호출find()값이unit_price보다 작고 이 아닌 문서와 일치하는 쿼리 필터하다12.00를 에 전달합니다.category"kitchen"일치하는 문서를
unit_price기준으로 내림차순으로 정렬하기 위해sort()메서드를find()에 연결합니다.
let mut cursor = my_coll .find(doc! { "$and": vec! [ doc! { "unit_price": doc! { "$lt": 12.00 } }, doc! { "category": doc! { "$ne": "kitchen" } } ] }) .sort(doc! { "unit_price": -1 }) .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 }
전체 파일 예시: 문서 찾기
이 예시 sample_restaurants 데이터베이스 의 restaurants 컬렉션 에서 쿼리 필터하다 와 일치하는 문서를 검색합니다. find() 메서드는 cuisine 필드 값이 "French"인 모든 문서를 반환합니다.
조회된 각 문서 Document 유형 또는 사용자 지정 데이터 유형 으로 모델링할 수 있습니다. 컬렉션의 데이터를 나타내는 데이터 유형 지정하려면 강조 표시된 줄의 <T> 유형 매개변수를 다음 값 중 하나로 바꿉니다.
<Document>: 컬렉션 문서를 BSON 문서로 조회하고 인쇄합니다.<Restaurant>: 코드 상단에 정의된Restaurant구조체의 인스턴스로 컬렉션 문서를 조회하고 인쇄합니다.
Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.
use mongodb::{ bson::doc, Client, Collection }; use futures::TryStreamExt; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let mut cursor = my_coll.find( doc! { "cuisine": "French" } ).await?; while let Some(doc) = cursor.try_next().await? { println!("{:#?}", doc); } Ok(()) }
use mongodb::{ bson::doc, sync::{Client, Collection} }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let mut cursor = my_coll.find( doc! { "cuisine": "French" } ).run()?; for result in cursor { println!("{:#?}", result?); } Ok(()) }
출력
컬렉션의 유형 매개변수에 따라 해당 코드 출력을 보려면 BSON Document Results 또는 Restaurant Struct Results 탭 선택합니다.
... Some( Document({ "_id": ObjectId( "...", ), ... "name": String( "Cafe Un Deux Trois", ), ... }), ), Some( Document({ "_id": ObjectId( "...", ), ... "name": String( "Calliope", ), ... }), ) ...
... Restaurant { name: "Cafe Un Deux Trois", cuisine: "French", } Restaurant { name: "Calliope", cuisine: "French", } ...
find_one() 예제
이 예에서는 다음 조치를 수행합니다.
find_one()메서드 호출unit_price20.00보다 작거나 같은 문서와 일치하는 쿼리 필터하다 를find_one()에 전달합니다.일치하는 처음 두 문서를 건너뛰기 위해
skip()메서드를find_one()으)로 연결합니다.
let result = my_coll .find_one(doc! { "unit_price": doc! { "$lte": 20.00 } }) .skip(2) .await?; println!("{:#?}", result);
Some( Inventory { item: "watering can", category: "garden", unit_price: 11.99, }, )
전체 파일 예시: 문서 찾기
이 예시 sample_restaurants 데이터베이스 의 restaurants 컬렉션 에서 쿼리 필터하다 와 일치하는 문서 조회합니다. find_one() 메서드는 name 필드 의 값이 "Tompkins Square Bagels"인 첫 번째 문서 반환합니다.
조회된 문서 Document 유형 또는 사용자 지정 데이터 유형 으로 모델링할 수 있습니다. 컬렉션의 데이터를 나타내는 데이터 유형 지정하려면 강조 표시된 줄의 <T> 유형 매개변수를 다음 값 중 하나로 바꿉니다.
<Document>: 컬렉션 문서를 BSON 문서로 조회하고 인쇄합니다.<Restaurant>: 코드 상단에 정의된Restaurant구조체의 인스턴스로 컬렉션 문서를 조회하고 인쇄합니다.
Asynchronous 또는 Synchronous 탭을 선택하여 각 런타임에 해당하는 코드를 확인합니다.
use mongodb::{ bson::doc, Client, Collection }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } async fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri).await?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let result = my_coll.find_one( doc! { "name": "Tompkins Square Bagels" } ).await?; println!("{:#?}", result); Ok(()) }
use mongodb::{ bson::doc, sync::{Client, Collection} }; use serde::{ Deserialize, Serialize }; struct Restaurant { name: String, cuisine: String, } fn main() -> mongodb::error::Result<()> { let uri = "<connection string>"; let client = Client::with_uri_str(uri)?; // Replace <T> with the <Document> or <Restaurant> type parameter let my_coll: Collection<T> = client .database("sample_restaurants") .collection("restaurants"); let result = my_coll.find_one( doc! { "name": "Tompkins Square Bagels" } ).run()?; println!("{:#?}", result); Ok(()) }
출력
컬렉션의 유형 매개변수에 따라 해당 코드 출력을 보려면 BSON Document Result 또는 Restaurant Struct Result 탭 선택합니다.
Some( Document({ "_id": ObjectId( "...", ), ... "name": String( "Tompkins Square Bagels", ), ... }), )
Some( Restaurant { name: "Tompkins Square Bagels", cuisine: "American", }, )
집계 작업
애그리게이션 작업을 사용하여 collection에서 데이터를 검색하고 변환합니다. aggregate() 메서드를 사용하여 애그리게이션 작업을 수행할 수 있습니다.
문서 데이터 집계
aggregate() 메서드는 집계 파이프라인 을 매개 변수로 사용합니다. 집계 파이프라인에는 데이터를 변환하는 방법을 지정하는 하나 이상의 단계 가 포함됩니다. 단계에는 애그리게이션 연산자(접두사 $)와 해당 연산자에 대한 필수 매개변수가 포함됩니다.
애그리게이션에 대해 자세히 알아보고 애그리게이션 예제를 보려면 애그리 게이션 가이드를 참조하세요.
이 메서드는 결과 문서를 Cursor 유형으로 반환합니다. 집계 파이프라인에 $match 단계가 포함되어 있지 않은 경우 파이프라인은 컬렉션의 모든 문서를 처리합니다.
애그리게이션 동작 수정
AggregateOptions 옵션 빌더 메서드를 aggregate() 에 연결하여 aggregate() 메서드의 동작을 수정할 수 있습니다.
다음 표에서는 해당 빌더 메서드를 호출하여 설정하다 수 있는 일반적으로 사용되는 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() 메서드를 호출하는 방법을 보여 줍니다.
$groupcategory필드 의 각 값에 대해unit_price필드 의 평균을 계산하는 단계$sortavg_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).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 문서를 참조하세요.