Docs Menu
Docs Home
/ / /
Java 동기화 드라이버
/ /

문서 수 계산

이 가이드 에서는 MongoDB 컬렉션의 문서 수를 계산하는 방법을 학습 수 있습니다. MongoCollection 클래스에는 컬렉션 의 문서 수를 계산하기 위해 호출할 수 있는 두 가지 인스턴스 메서드가 있습니다.

  • countDocuments() 컬렉션에서 지정된 쿼리와 일치하는 문서 수를 반환합니다. 빈 쿼리 필터를 지정하면 메서드는 컬렉션에 있는 총 문서 수를 반환합니다.

  • estimatedDocumentCount() 컬렉션 메타데이터를 기반으로 컬렉션 내 문서 수의 추정치를 반환합니다. 이 메서드를 사용할 때는 쿼리를 지정할 수 없습니다.

estimatedDocumentCount() 메서드는 전체 컬렉션을 스캔하는 대신 컬렉션의 메타데이터를 사용하기 때문에 countDocuments() 메서드보다 빠릅니다. countDocuments() 메서드는 문서 수의 정확한 개수를 반환하고 필터 지정을 지원합니다.

countDocuments() 를 사용하여 컬렉션의 총 문서 수를 반환하는 경우 컬렉션 스캔을 방지하여 성능을 향상시킬 수 있습니다. 이렇게 하려면 힌트 를 사용하여 _id 필드에 내장된 인덱스를 활용합니다. 빈 쿼리 매개 변수를 사용하여 countDocuments() 를 호출할 때만 이 기술을 사용합니다.

CountOptions opts = new CountOptions().hintString("_id_");
long numDocuments = collection.countDocuments(new BsonDocument(), opts);

countDocuments() 메서드를 호출할 때 필요에 따라 쿼리 필터 매개변수를 전달할 수 있습니다. estimatedDocumentCount()를 호출할 때는 어떤 매개변수도 전달할 수 없습니다.

중요

Stable API V1 및 MongoDB Server 이슈

"strict" 옵션으로 Stable API V1 을(를) 사용하고 MongoDB Server 버전이 5.0.0~5.0.8(포함)인 경우 estimatedDocumentCount() 에 대한 메서드 호출 시 서버 버그로 인해 오류가 발생할 수 있습니다.

이 문제를 방지하려면 MongoDB Server 5.0.9로 업그레이드하거나 Stable API "strict" 옵션을 false로 설정합니다.

호출 동작을 지정하기 위해 다음 메서드 중 하나에 선택적 매개변수를 전달할 수도 있습니다.

메서드
선택적 매개변수 클래스
설명

countDocuments()

CountOptions

limit() 메서드를 사용하여 계산할 최대 문서 수를 지정하거나 maxTime() 메서드를 사용하여 최대 실행 시간을 지정할 수 있습니다.

estimatedDocumentCount()

EstimatedDocumentCountOptions

maxTime() 메서드를 사용하여 최대 실행 시간을 지정할 수 있습니다.

두 메서드 모두 일치하는 문서 수를 long 기본으로 반환합니다.

참고

설정 예시

이 예시 연결 URI를 사용하여 MongoDB 인스턴스 에 연결합니다. MongoDB 인스턴스 에 연결하는 방법에 대해 자세히 학습 MongoClient 만들기 가이드 참조하세요. 이 예시 movies sample_mflix Atlas 샘플 데이터 세트에 포함된 데이터베이스 의 컬렉션 도 사용합니다. Atlas 시작하기가이드에 따라 MongoDB Atlas 의 무료 계층 에서 데이터베이스 에 로드할 수 있습니다.

다음 예는 sample_mflix 데이터베이스의 movies 컬렉션에 있는 문서 수를 추정하고 countries 필드에 Canada가 있는 movies 컬렉션의 정확한 문서 수를 반환합니다.

/**
* This file demonstrates how to open a change stream by using the Java driver.
* It connects to a MongoDB deployment, accesses the "sample_mflix" database, and listens
* to change events in the "movies" collection. The code uses a change stream with a pipeline
* to only filter for "insert" and "update" events.
*/
package usage.examples;
import static com.mongodb.client.model.Filters.eq;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoException;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
public class CountDocuments {
public static void main(String[] args) {
// Replace the uri string with your MongoDB deployment's connection string
String uri = "<connection string uri>";
try (MongoClient mongoClient = MongoClients.create(uri)) {
MongoDatabase database = mongoClient.getDatabase("sample_mflix");
MongoCollection<Document> collection = database.getCollection("movies");
Bson query = eq("countries", "Spain");
// Retrieves and prints the estimated number of documents in the collection
long estimatedCount = collection.estimatedDocumentCount();
System.out.println("Estimated number of documents in the movies collection: " + estimatedCount);
// Retrieves and prints the number of documents with a "countries" value of "Spain"
long matchingCount = collection.countDocuments(query);
System.out.println("Number of movies from Spain: " + matchingCount);
}
}
}

앞의 샘플 코드를 실행하면 다음과 같은 출력이 표시됩니다(정확한 숫자는 데이터에 따라 다를 수 있음).

Estimated number of documents in the movies collection: 23541
Number of movies from Spain: 755

Legacy API

레거시 API 사용하는 경우 레거시 API 가이드의 FAQ 섹션 을 참조하여 이 코드 예시에 적용해야 하는 변경 사항을 학습.

문서 수를 계산하는 데 사용되는 클래스 및 메서드에 대한 자세한 내용은 다음 API 설명서를 참조하세요.

돌아가기

문서 찾기

이 페이지의 내용