개요
이 가이드에서는 MongoDB .NET/C# 드라이버를 사용하여 읽기 작업을 통해 MongoDB 컬렉션에서 데이터를 조회하는 방법을 배울 수 있습니다. Find()
메서드를 호출하여 기준의 설정과 일치하는 문서를 조회할 수 있습니다.
팁
인터랙티브 랩
이 페이지에는 Find()
메서드를 사용하여 데이터를 조회하는 방법을 보여주는 짧은 인터랙티브 실습이 포함되어 있습니다. MongoDB 또는 코드 편집기를 설치하지 않고도 브라우저 창에서 직접 이 실습을 완료할 수 있습니다.
실습을 시작하려면 페이지 상단의 Open Interactive Tutorial 버튼을 클릭하세요. 실습을 전체 화면 형식으로 확장하려면 실습 창의 오른쪽 상단 모서리에 있는 전체 화면 버튼(⛶)을 클릭합니다.
샘플 데이터
이 가이드 의 예제에서는 sample_restaurants.restaurants
Atlas 샘플 데이터 세트의 컬렉션 사용합니다. 무료 MongoDB Atlas cluster 생성하고 샘플 데이터 세트를 로드하는 방법을 학습 .NET/ C# 드라이버 시작하기 를 참조하세요.
이 페이지의 예시에서는 다음 Restaurant
, Address
및 GradeEntry
클래스를 모델로 사용합니다:
public class Restaurant { public ObjectId Id { get; set; } public string Name { get; set; } [ ] public string RestaurantId { get; set; } public string Cuisine { get; set; } public Address Address { get; set; } public string Borough { get; set; } public List<GradeEntry> Grades { get; set; } }
public class Address { public string Building { get; set; } [ ] public double[] Coordinates { get; set; } public string Street { get; set; } [ ] public string ZipCode { get; set; } }
public class GradeEntry { public DateTime Date { get; set; } public string Grade { get; set; } public float? Score { get; set; } }
참고
restaurants
컬렉션 의 문서는 대소문자 명명 규칙을 사용합니다. 이 가이드 의 예제에서는 ConventionPack
를 사용하여 컬렉션 의 필드를 파스칼식 대/소문자로 역직렬화하고 Restaurant
클래스의 속성에 매핑합니다.
사용자 지정 직렬화에 대해 자세히 알아보려면 사용자 지정 직렬화를참조하세요.
문서 찾기
컬렉션에서 문서를 검색하려면 Find()
메서드를 사용합니다. Find()
메서드는 쿼리 필터를 사용하여 일치하는 모든 문서를 반환합니다. 쿼리 필터는 쿼리에서 검색하려는 문서를 지정하는 객체입니다.
쿼리 필터에 대해 자세히 학습 쿼리 필터 만들기를 참조하세요.
하나의 문서 찾기
컬렉션에서 단일 문서를 찾으려면 찾으려는 문서의 기준을 지정하는 쿼리 필터를 전달한 다음 FirstOrDefault()
또는 FirstOrDefaultAsync()
메서드를 체인으로 연결합니다. 쿼리 필터와 일치하는 문서가 두 개 이상인 경우, 이 메서드는 조회된 결과에서 처음 일치하는 문서를 반환합니다. 쿼리 필터와 일치하는 문서가 없는 경우 메서드는 null
을 반환합니다.
var restaurants = _restaurantsCollection.Find(filter).FirstOrDefault();
var restaurants = await _restaurantsCollection.Find(filter).FirstOrDefaultAsync();
Find()
메서드를 사용하여 단일 문서를 찾는 예시 전체를 보려면 추가 정보를 참조하세요.
여러 문서 찾기
컬렉션에서 여러 문서를 찾으려면 검색하려는 문서의 기준을 지정하는 Find()
메서드에 쿼리 필터를 전달합니다.
커서를 사용하여 Find()
메서드에서 반환한 문서를 반복할 수 있습니다. 커서는 애플리케이션이 주어진 시간에 데이터베이스 결과의 하위 집합만 메모리에 유지하면서 데이터베이스 결과를 반복할 수 있는 메커니즘입니다. 커서는 Find()
메소드가 많은 양의 문서를 반환할 때 유용합니다.
커서를 사용하여 문서를 반복하려면 찾으려는 문서의 기준을 지정하는 Find()
메서드에 쿼리 필터를 전달한 다음 ToCursor()
또는 ToCursorAsync()
메서드를 연결합니다. 동기 또는 비동기 예시를 보려면 해당 탭을 선택합니다.
var restaurants = _restaurantsCollection.Find(filter).ToCursor();
var restaurants = await _restaurantsCollection.Find(filter).ToCursorAsync();
적은 수의 문서를 반환하거나 결과를 List
객체로 반환해야 하는 경우 ToList()
또는 ToListAsync()
메서드를 사용합니다.
컬렉션에서 여러 문서를 찾아 메모리에 목록으로 보관하려면 찾으려는 문서의 기준을 지정하는 Find()
메서드에 쿼리 필터를 전달한 다음 ToList()
또는 ToListAsync()
메서드를 연결합니다. 동기 또는 비동기 예시를 보려면 해당 탭을 선택합니다.
var restaurants = _restaurantsCollection.Find(filter).ToList();
var restaurants = await _restaurantsCollection.Find(filter).ToListAsync();
Find()
메서드를 사용하여 여러 문서를 찾는 전체 예시를 보려면 추가 정보를 참조하세요.
참고
모든 문서 찾기
컬렉션의 모든 문서를 찾으려면 Find()
메서드에 빈 필터를 전달합니다.
var filter = Builders<Restaurant>.Filter.Empty; var allRestaurants = _restaurantsCollection.Find(filter);
Find()
메서드를 사용하여 모든 문서를 찾는 실행 가능한 예시 전체를 보려면 추가 정보를 참조하세요.
검색 동작 수정
FindOptions
객체를 전달하여 Find()
메서드의 동작을 수정할 수 있습니다.
다음 메서드를 통해 일반적으로 사용되는 옵션을 구성할 수 있습니다
메서드 | 설명 |
---|---|
| Gets or sets the maximum number of documents within each
batch returned in a query result. If batchSize is not set, the Find()
method has an initial batch size of 101 documents and a maximum size of 16
mebibytes (MiB) for each subsequent batch. This option can enforce a smaller
limit than 16 MiB, but not a larger one. If you set batchSize to a limit that
results in batches larger than 16 MiB, this option has no effect and the
Find() method uses the default batch size. |
| Sets the collation options. See the
Collation section of this page for more information. |
| Sets the comment to the query to make looking in the profiler logs easier. |
| Sets the hint for which index to use. |
| Sets the maximum execution time on the server for this operation. |
사용 가능한 옵션의 전체 목록을 보려면 FindOptions 속성을 참조하세요.
데이터 정렬
작업에 대한 데이터 정렬을 구성하려면 데이터 정렬 클래스의 인스턴스 만듭니다.
다음 표에서는 Collation
생성자가 허용하는 매개변수에 대해 설명합니다. 또한 각 설정의 값을 읽는 데 사용할 수 있는 해당 클래스 속성 나열되어 있습니다.
Parameter | 설명 | 클래스 속성 |
---|---|---|
| Specifies the International Components for Unicode (ICU) locale. For a list of
supported locales,
see Collation Locales and Default Parameters
in the MongoDB Server Manual. If you want to use simple binary comparison, use the Collation.Simple static
property to return a Collation object with the locale set to "simple" .Data Type: string |
|
| (Optional) Specifies whether to include case comparison. When this argument is true , the driver's behavior depends on the value of
the strength argument:- If strength is CollationStrength.Primary , the driver compares base
characters and case.- If strength is CollationStrength.Secondary , the driver compares base
characters, diacritics, other secondary differences, and case.- If strength is any other value, this argument is ignored.When this argument is false , the driver doesn't include case comparison at
strength level Primary or Secondary .Data Type: boolean Default: false |
|
| (Optional) Specifies the sort order of case differences during tertiary level comparisons. Data Type: CollationCaseFirst Default: CollationCaseFirst.Off |
|
| (Optional) Specifies the level of comparison to perform, as defined in the
ICU documentation. Data Type: CollationStrength Default: CollationStrength.Tertiary |
|
| (Optional) Specifies whether the driver compares numeric strings as numbers. If this argument is true , the driver compares numeric strings as numbers.
For example, when comparing the strings "10" and "2", the driver treats the values
as 10 and 2, and finds 10 to be greater.If this argument is false or excluded, the driver compares numeric strings
as strings. For example, when comparing the strings "10" and "2", the driver
compares one character at a time. Because "1" is less than "2", the driver finds
"10" to be less than "2".For more information, see Collation Restrictions
in the MongoDB Server manual. Data Type: boolean Default: false |
|
| (Optional) Specifies whether the driver considers whitespace and punctuation as base
characters for purposes of comparison. Data Type: CollationAlternate Default: CollationAlternate.NonIgnorable (spaces and punctuation are
considered base characters) |
|
| (Optional) Specifies which characters the driver considers ignorable when
the alternate argument is CollationAlternate.Shifted .Data Type: CollationMaxVariable Default: CollationMaxVariable.Punctuation (the driver ignores punctuation
and spaces) |
|
| (Optional) Specifies whether the driver normalizes text as needed. Most text doesn't require normalization. For more information about
normalization, see the ICU documentation. Data Type: boolean Default: false |
|
| (Optional) Specifies whether strings containing diacritics sort from the back of the string
to the front. Data Type: boolean Default: false |
|
데이터 정렬에 대한 자세한 내용은 MongoDB Server 매뉴얼의 데이터 정렬 페이지를 참조하세요.
예시
이 예에서는 다음 조치를 수행합니다.
cuisine
필드에 'Pizza'가 포함된 모든 문서를 찾습니다..
BatchSize
를3
으로 설정결과를 커서에 저장
커서가 참고한 문서를 인쇄합니다.
var filter = Builders<Restaurant>.Filter.Eq("cuisine", "Pizza"); var findOptions = new FindOptions { BatchSize = 3 }; using (var cursor = _restaurantsCollection.Find(filter, findOptions).ToCursor()) { foreach (var r in cursor.ToEnumerable()) { WriteLine(r.Name); } }
Pizza Town Victoria Pizza ...
추가 정보
쿼리 필터에 대해 자세히 학습 쿼리 필터 만들기를 참조하세요.
LINQ를 사용하여 쿼리를 지정하는 방법을 학습 애그리게이션 작업을 위한 LINQ 구문 참조하세요.
찾기 작업의 실행 가능한 예는 다음과 같은 사용의 예를 참조하세요.
API 문서
이 가이드에서 설명하는 메서드나 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.