문서 메뉴
문서 홈
/ / /
Kotlin Sync 드라이버
/

문서 수 계산

이 페이지의 내용

  • 개요
  • 샘플 데이터
  • 정확한 개수 조회
  • 모든 문서 계산
  • 특정 문서 수 계산
  • 카운트 동작 사용자 지정
  • 예상 개수 조회
  • 예상 카운트 동작 사용자 지정
  • API 문서

이 가이드에서는 컬렉션에 있는 문서 수의 정확한 개수와 예상 개수를 검색하는 방법을 알아볼 수 있습니다.

이 가이드의 예제에서는 Atlas 샘플 데이터 세트sample_mflix 데이터베이스에 있는 movies 컬렉션을 사용합니다. 무료 MongoDB Atlas 클러스터를 생성하고 샘플 데이터 세트를 로드하는 방법을 알아보려면 Atlas 시작하기 가이드를 참조하세요.

다음 Kotlin 데이터 클래스는 이 컬렉션의 문서를 모델링합니다.

data class Movie(
@BsonId
val id: ObjectId,
val title: String
)

컬렉션에 있는 문서 수를 계산하려면 countDocuments() 메서드를 사용합니다. 지정된 검색 기준과 일치하는 문서 수를 계산하려면 countDocuments() 메서드에 쿼리 필터를 전달합니다.

쿼리 지정에 대해 자세히 알아보려면 쿼리 지정을 참조하세요.

컬렉션에 있는 모든 문서의 개수를 반환하려면 다음 예제와 같이 인수 없이 countDocuments() 메서드를 호출합니다.

println(collection.countDocuments())

특정 검색 기준과 일치하는 문서 수를 반환하려면 countDocuments() 메서드에 쿼리를 지정합니다. 다음 예에서는 movies 컬렉션에서 year 필드 값이 1930 인 모든 문서의 개수를 출력합니다.

println(collection.countDocuments(eq("year", "1930")))

countDocuments() 메서드는 카운트 작업을 구성하는 데 사용할 수 있는 옵션을 나타내는 CountOptions 객체 형식의 선택적 매개변수를 허용합니다. 새 CountOptions 객체를 인스턴스화하고 해당 메서드를 사용하여 객체의 필드를 설정한 다음 countDocuments() 메서드에 전달하여 이러한 옵션을 설정할 수 있습니다. 옵션을 지정하지 않으면 드라이버는 카운트 작업을 사용자 지정하지 않습니다.

다음 표에서는 countDocuments() 을(를) 사용자 지정하기 위해 설정할 수 있는 옵션에 대해 설명합니다.

옵션
설명
comment
Specifies a comment to attach to the operation.
skip
Sets the number of documents to skip before returning results.
limit
Sets the maximum number of documents to count. Must be a positive integer.
maxTime
Sets the maximum amount of time to allow the operation to run, in milliseconds.
collation
Specifies the kind of language collation to use when sorting results. For more information, see Collation in the MongoDB Server manual.
hint
Sets the index to scan for documents.

다음 예제에서는 CountOptions 객체를 사용하여 countDocuments() 작업에 주석을 추가합니다.

val options = CountOptions().comment("Retrieving count")
collection.countDocuments(Filters.empty(), options)

컬렉션에 있는 문서 수의 추정치를 조회하려면 estimatedDocumentCount() 메서드를 사용합니다. 이 메서드는 컬렉션 메타데이터를 기반으로 문서의 양을 추정하므로 정확한 개수를 계산하는 것보다 빠를 수 있습니다.

다음 예에서는 컬렉션의 예상 문서 수를 출력합니다.

print(collection.estimatedDocumentCount())

estimatedDocumentCount() 메서드는 카운트 작업을 구성하는 데 사용할 수 있는 옵션을 나타내는 EstimatedDocumentCountOptions 객체 형식의 선택적 매개변수를 허용합니다. 새 EstimatedDocumentCountOptions 객체를 인스턴스화하고 해당 메서드를 사용하여 객체의 필드를 설정한 다음 estimatedDocumentCount() 메서드에 전달하여 이러한 옵션을 설정할 수 있습니다. 옵션을 지정하지 않으면 드라이버는 카운트 작업을 사용자 지정하지 않습니다.

다음 표에서는 estimatedDocumentCount() 을(를) 사용자 지정하기 위해 설정할 수 있는 옵션에 대해 설명합니다.

옵션
설명
comment
Specifies a comment to attach to the operation.
maxTime
Specifies the maximum amount of time to allow the operation to run, in milliseconds.

다음 예제에서는 EstimatedDocumentCountOptions 객체를 사용하여 estimatedDocumentCount() 작업에 주석을 추가합니다.

val options = EstimatedDocumentCountOptions().comment("Retrieving count")
collection.estimatedDocumentCount(options)

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

돌아가기

반환할 문서 지정

다음

고유 필드 값 검색