Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
C#/ .NET 드라이버
/ /

문서 수 계산

이 가이드에서는 컬렉션의 문서 수에 대한 개의 정확한 예상 개수를 얻는 방법에 대해 알아볼 수 있습니다.

이 가이드의 예에서는 students 컬렉션의 다음 문서를 사용합니다.

{ "_id": 1, "name": "Jonathon Howard ", "finalGrade": 87.5 }
{ "_id": 2, "name": "Keisha Freeman", "finalGrade": 12.3 }
{ "_id": 3, "name": "Wei Zhang", "finalGrade": 99.0 }
{ "_id": 4, "name": "Juan Gonzalez", "finalGrade": 85.5 }
{ "_id": 5, "name": "Erik Trout", "finalGrade": 72.3 }
{ "_id": 6, "name": "Demarcus Smith", "finalGrade": 88.8 }

다음 Student 클래스는 아래 컬렉션에 있는 문서를 모델링합니다.

public class Student {
public int Id { get; set; }
public string Name { get; set; }
public double FinalGrade { get; set; }
}

참고

students 컬렉션의 문서는 카멜 케이스 명명 규칙을 사용합니다. 이 가이드의 예시에서는 ConventionPack 사용하여 컬렉션의 필드를 파스칼식 대/소문자로 역직렬화하고 Student 클래스의 속성에 매핑합니다.

사용자 지정 직렬화에 대해 자세히 알아보려면 사용자 지정 직렬화를 참조하세요.

쿼리 필터와 일치하는 문서 수를 계산하려면 CountDocuments() 메서드를 사용하세요. 빈 쿼리 필터를 전달하는 경우 이 메서드는 컬렉션에 있는 총 문서 수를 반환합니다.

다음 예에서는 finalGrade80보다 작은 문서 수를 계산합니다.

var filter = Builders<Student>.Filter.Lt(s => s.FinalGrade, 80.0);
var count = _myColl.CountDocuments(filter);
Console.WriteLine("Number of documents with a final grade less than 80: " + count);
Number of documents with a final grade less than 80: 2

CountOptions 유형을 매개 변수로 전달하여 CountDocuments()의 동작을 수정할 수 있습니다. 옵션을 지정하지 않으면 드라이버는 기본값을 사용합니다.

CountOptions 객체에서 다음 속성을 설정할 수 있습니다.

속성
설명

Collation

The type of language collation to use when sorting results. See the Collation section of this page for more information.
Default: null

Hint

The index to use to scan for documents to count.
Default: null

Limit

The maximum number of documents to count.
Default: 0

MaxTime

The maximum amount of time that the query can run on the server.
Default: null

Skip

The number of documents to skip before counting.
Default: 0

CountDocuments()를 사용하여 컬렉션의 총 문서 수를 반환하면 MongoDB는 컬렉션 스캔을 수행합니다. _id 필드에 기본 제공되는 인덱스를 활용에 대한 힌트를 참고하여 컬렉션 스캔을 피하고 이 메서드의 성능을 향상시킬 수 있습니다. 빈 쿼리 매개 변수를 사용하여 CountDocuments()를 호출할 때만 이 방법을 사용합니다.

var filter = Builders<Student>.Filter.Empty;
CountOptions opts = new CountOptions(){Hint = "_id_"};
var count = collection.CountDocuments(filter, opts);

작업에 대한 데이터 정렬을 구성하려면 데이터 정렬 클래스의 인스턴스 만듭니다.

다음 표에서는 Collation 생성자가 허용하는 매개변수에 대해 설명합니다. 또한 각 설정의 값을 읽는 데 사용할 수 있는 해당 클래스 속성 도 나열되어 있습니다.

Parameter
설명
클래스 속성

locale

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

Locale

caseLevel

(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

CaseLevel

caseFirst

(Optional) Specifies the sort order of case differences during tertiary level comparisons.

Default: CollationCaseFirst.Off

CaseFirst

strength

(Optional) Specifies the level of comparison to perform, as defined in the ICU documentation.

Default: CollationStrength.Tertiary

Strength

numericOrdering

(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

NumericOrdering

alternate

(Optional) Specifies whether the driver considers whitespace and punctuation as base characters for purposes of comparison.

Default: CollationAlternate.NonIgnorable (spaces and punctuation are considered base characters)

Alternate

maxVariable

(Optional) Specifies which characters the driver considers ignorable when the alternate argument is CollationAlternate.Shifted.

Default: CollationMaxVariable.Punctuation (the driver ignores punctuation and spaces)

MaxVariable

normalization

(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

Normalization

backwards

(Optional) Specifies whether strings containing diacritics sort from the back of the string to the front.

Data Type: boolean
Default: false

Backwards

데이터 정렬에 대한 자세한 내용은 MongoDB Server 매뉴얼의 데이터 정렬 페이지를 참조하세요.

컬렉션의 총 문서 수를 추정하려면 EstimatedDocumentCount() 메서드를 사용합니다.

참고

EstimatedDocumentCount() 메서드는 전체 컬렉션을 스캔하는 대신 컬렉션의 메타데이터를 사용하기 때문에 CountDocuments() 메서드보다 빠릅니다.

EstimatedDocumentCountOptions 유형을 매개 변수로 전달하여 EstimatedDocumentCount()의 동작을 수정할 수 있습니다. 옵션을 지정하지 않으면 드라이버는 기본값을 사용합니다.

EstimatedDocumentCountOptions 객체에서 다음 속성을 설정할 수 있습니다.

속성
설명

MaxTime

The maximum amount of time that the query can run on the server.
Default: null

다음 예는 students 컬렉션의 문서 수를 추정하는 예입니다:

var count = _myColl.EstimatedDocumentCount();
Console.WriteLine("Estimated number of documents in the students collection: " + count);
Estimated number of documents in the students collection: 6

Count() 빌더 메서드를 사용하여 집계 파이프라인의 문서 수를 계산할 수 있습니다.

다음 예시에서는 다음 작업을 수행합니다:

  • FinalGrade 값이 80보다 큰 문서를 찾기 위한 일치 단계 지정

  • 기준과 일치하는 문서의 수 계산

var filter = Builders<Student>
.Filter.Gt(s => s.FinalGrade, 80);
var result = _myColl.Aggregate().Match(filter).Count();
Console.WriteLine("Number of documents with a final grade more than 80: " + result.First().Count);
Number of documents with a final grade more than 80: 4

언급된 작업에 대해 자세히 알아보려면 다음 가이드를 참조하세요.

이 가이드에서 설명하는 메서드나 유형에 대해 자세히 알아보려면 다음 API 설명서를 참조하세요.

돌아가기

반환할 필드 지정

이 페이지의 내용