AI 에이전트의 경우: 문서 인덱스는 https://www.mongodb.com/ko-kr/docs/llms.txt에서 사용할 수 있으며, 모든 페이지의 마크다운 버전은 어떤 URL 경로에 .md를 추가하여 사용할 수 있습니다.
Docs Menu

문서 수 계산

이 가이드에서는 컬렉션에 있는 문서 수를 정확하게 추정하여 집계하는 방법에 대해 알아볼 수 있습니다.

이 가이드의 예에서는 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() 메서드를 사용하세요. 빈 쿼리 필터를 전달하는 경우 이 메서드는 컬렉션에 있는 총 문서 수를 반환합니다.

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

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);

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

계산할 문서를 스캔할 때 사용할 인덱스입니다.
기본값: null

Limit

세어야 할 문서의 최대 개수.
기본값: 0

MaxTime

서버에서 쿼리를 실행할 수 있는 최대 시간입니다.
기본값: null

Skip

계산하기 전에 건너랄을 문서 수입니다.
기본값: 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

(선택 사항) 대/소문자 비교 포함 여부를 지정합니다.

이 인수가 true인 경우 드라이버의 동작은 strength 인수의 값에 따라 달라집니다.

- strength 가 CollationStrength.Primary인 경우 드라이버는 기본 문자와 대소문자를 비교합니다.
- strength 가 CollationStrength.Secondary인 경우 드라이버는 기본 문자, 발음 부호, 기타 세컨더리 차이 및 대소문자를 비교합니다.
- strength 이 기타 값인 경우 이 인수는 무시됩니다.

이 인수가 false인 경우 드라이버는 Primary 또는 Secondary 수준의 강도에서 대소문자 비교를 포함하지 않습니다.

데이터 유형: boolean
기본값: false

CaseLevel

caseFirst

(선택 사항) 3차 수준 비교 시 대소문자 차이의 정렬 순서를 지정합니다.

데이터 유형: CollationCaseFirst
기본값: CollationCaseFirst.Off

CaseFirst

strength

(선택 사항) ICU 문서에 정의된 대로 수행할 비교 수준을 지정합니다.

데이터 유형: CollationStrength
기본값: 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

(선택 사항) 비교를 위해 드라이버가 공백과 구두점을 기본 문자로 간주할지 여부를 지정합니다.

데이터 유형: CollationAlternate
기본값: CollationAlternate.NonIgnorable (공백과 구두점은 기본 문자로 간주됨)

Alternate

maxVariable

(선택 사항) alternate이(가) CollationAlternate.Shifted일 때 드라이버가 무시할 수 있는 것으로 간주하는 문자를 지정합니다.

데이터 유형: CollationMaxVariable
기본값: CollationMaxVariable.Punctuation (드라이버가 문장 부호와 공백을 무시함)

MaxVariable

normalization

(선택 사항) 드라이버가 필요에 따라 텍스트를 정규화할지 여부를 지정합니다.

대부분의 텍스트는 정규화가 필요하지 않습니다. 정규화에 대한 자세한 내용은 ICU 설명서를 참조하세요.

데이터 유형: boolean
기본값: false

Normalization

backwards

(선택 사항) 분음 부호가 포함된 string이 string의 뒤쪽에서 앞쪽으로 정렬되는지 지정합니다.

데이터 유형: boolean
기본값: false

Backwards

For more information about collation, see the Collation page in the MongoDB Server manual.

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

참고

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

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

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

속성
설명

MaxTime

서버에서 쿼리를 실행할 수 있는 최대 시간입니다.
기본값: null

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

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

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);

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

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