Docs Menu
Docs Home
/ /

Retrieve Data

이 가이드에서는 읽기 작업 을 사용하여 MongoDB collection에서 데이터를 검색하는 방법에 대해 설명합니다. 읽기 작업은 서버에서 문서를 검색하는 명령입니다.

읽기 작업에는 두 가지 유형이 있습니다.

  • collection에서 문서를 검색할 수 있는 찾기 작업

  • collection의 데이터를 변환할 수 있는 애그리게이션 작업

이 가이드에는 다음 섹션이 포함되어 있습니다.

  • 예제용 샘플 데이터는 읽기 작업 예제에서 사용되는 샘플 데이터를 제공합니다.

  • 찾기 작업 에서는 운전자 를 사용하여 찾기 작업을 실행하는 방법을 설명합니다.

  • 애그리게이션 작업 에서는 운전자 를 사용하여 집계 작업을 실행하는 방법을 설명합니다.

  • 추가 정보에서 이 가이드에 언급된 유형 및 메소드에 대한 리소스 및 API 문서 링크를 찾을 수 있습니다.

이 가이드의 예에서는 다음 샘플 문서를 사용합니다. 각 문서는 매장 재고에 있는 품목을 나타내며 분류 및 단가에 대한 정보를 포함합니다.

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() 메서드를 사용합니다. 이 메서드는 쿼리 필터를 매개 변수로 사용합니다. 쿼리 필터는 문서가 일치시킬 기준을 형성하는 필드와 값으로 구성됩니다.

문서가 필터 기준과 일치하면 메서드는 값이 SomeResult<Option<T>> 유형을 반환합니다. 필터 기준과 일치하는 문서가 없는 경우 find_one() 는 값이 NoneResult<Option<T>> 유형을 반환합니다.

이 메서드를 사용하여 데이터를 조회 하는 예시 를 보려면 find_one() 예시 를 참조하세요.

FindOptions 인스턴스를 매개 변수로 전달하여 find() 의 동작을 수정하고 FindOneOptions 인스턴스를 전달하여 find_one() 의 동작을 수정할 수 있습니다.

각 설정에 기본값을 사용하려면 None 값을 옵션 매개 변수로 지정합니다.

다음 표에서는 FindOptionsFindOneOptions 에서 지정할 수 있는 일반적으로 사용되는 설정을 설명합니다.

설정
설명

collation

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: None

hint

The index to use for the operation. To learn more about indexes, see Indexes in the Server manual.

Type: Hint
Default: None

projection

The projection to use when returning results.

Type: Document
Default: None

read_concern

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

skip

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: u64
Default: None

sort

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: Document
Default: None

참고

인스턴스화 옵션

Rust 드라이버는 FindOneOptions 또는 FindOptions 와 같은 다양한 유형을 생성하기 위해 빌더 디자인 패턴을 구현합니다. 각 유형의 builder() 메서드를 사용하여 옵션 빌더 함수를 한 번에 하나씩 연결하여 옵션 인스턴스를 구성할 수 있습니다.

각 유형에 대해 지정할 수 있는 설정의 전체 목록은 FindOptionsFindOneOptions에 대한 API 설명서를 참조하세요.

다음 섹션에는 find()findOne() 메서드를 사용하여 필터 기준과 일치하는 샘플 문서를 조회하는 예가 포함되어 있습니다.

이 예에서는 다음 매개 변수를 사용하여 find() 메서드를 호출하는 방법을 보여 줍니다.

  • 값이 unit_price 보다 작고 이 아닌 문서와 일치하는 쿼리 필터입니다.12.00 category "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() 메서드를 호출하는 방법을 보여 줍니다.

  • 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 에서 지정할 수 있는 일반적으로 사용되는 설정에 대해 설명합니다.

설정
설명

allow_disk_use

Enables writing to temporary files. If true, aggregation stages can write data to the _tmp subdirectory in the dbPath directory.

Type: bool
Default: false

batch_size

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: u32
Default: 101 documents initially, 16 MB maximum for subsequent batches

collation

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: None

hint

The index to use for the operation. To learn more about indexes, see Indexes in the Server manual.

Type: Hint
Default: None

read_concern

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

write_concern

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 문서를 참조하세요.

돌아가기

엔터프라이즈 인증

이 페이지의 내용